Class: Kabk::ResourceBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/kabk/resource_builder.rb

Overview

DSL builder for resources

Instance Method Summary collapse

Constructor Details

#initialize(resource) ⇒ ResourceBuilder

Returns a new instance of ResourceBuilder.



10
11
12
# File 'lib/kabk/resource_builder.rb', line 10

def initialize(resource)
  @resource = resource
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, **kwargs, &block) ⇒ Object

Delegate dynamic attribute setting (e.g. title, icon, plural_name)



15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/kabk/resource_builder.rb', line 15

def method_missing(method_name, *args, **kwargs, &block)
  if @resource.respond_to?("#{method_name}=")
    value = if kwargs.any? && args.empty?
              kwargs
            else
              args.first
            end
    @resource.send("#{method_name}=", value)
  else
    super
  end
end

Instance Method Details

#field(name, type:, form_type:, **attributes) ⇒ Object

Define a field with attributes

Raises:



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/kabk/resource_builder.rb', line 33

def field(name, type:, form_type:, **attributes)
  # Validate required keys per spec
  raise InvalidFieldError, "Field '#{name}' is missing 'type'" unless type
  raise InvalidFieldError, "Field '#{name}' is missing 'form_type'" unless form_type

  # Extract label, if not provided, default to titleized name
  label = attributes.delete(:label)
  if label.nil?
    label = attributes.select { |k, _v| [:fa, :en].include?(k) }
    label = name.to_s.capitalize.tr("_", " ") if label.empty?
    attributes.reject! { |k, _v| [:fa, :en].include?(k) }
  end

  f = Field.new(name: name, type: type, form_type: form_type, label: label, **attributes)
  @resource.fields << f
end

#permissions(**perms) ⇒ Object

Configure permissions explicitly



51
52
53
# File 'lib/kabk/resource_builder.rb', line 51

def permissions(**perms)
  @resource.permissions.merge!(perms)
end

#respond_to_missing?(method_name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


28
29
30
# File 'lib/kabk/resource_builder.rb', line 28

def respond_to_missing?(method_name, include_private = false)
  @resource.respond_to?("#{method_name}=") || super
end