Module: Subroutine::Fields::ClassMethods

Defined in:
lib/subroutine/fields.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



94
95
96
97
98
99
100
101
102
103
104
# File 'lib/subroutine/fields.rb', line 94

def method_missing(method_name, *args, &block)
  caster = ::Subroutine::TypeCaster.casters[method_name.to_sym]
  if caster
    field_name, options = args
    options ||= {}
    options[:type] = method_name.to_sym
    field(field_name, options)
  else
    super
  end
end

Instance Method Details

#field(field_name, options = {}) ⇒ Object Also known as: input



39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/subroutine/fields.rb', line 39

def field(field_name, options = {})
  config = ::Subroutine::Fields::Configuration.from(field_name, options)
  config.validate!

  self.field_configurations = field_configurations.merge(field_name.to_sym => config)

  ensure_field_accessors(config)

  config.groups.each do |group_name|
    ensure_group_accessors(group_name)
  end

  config
end

#fields_from(*things) ⇒ Object Also known as: inputs_from



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/subroutine/fields.rb', line 55

def fields_from(*things)
  options = things.extract_options!
  excepts = options.key?(:except) ? Array(options.delete(:except)) : nil
  onlys = options.key?(:only) ? Array(options.delete(:only)) : nil

  things.each do |thing|
    local_excepts = excepts.map { |field| thing.get_field_config(field)&.related_field_names }.flatten.compact.uniq if excepts
    local_onlys = onlys.map { |field| thing.get_field_config(field)&.related_field_names }.flatten.compact.uniq if onlys

    thing.field_configurations.each_pair do |field_name, config|
      next if local_excepts&.include?(field_name)
      next if local_onlys && !local_onlys.include?(field_name)

      config.required_modules.each do |mod|
        include mod unless included_modules.include?(mod)
      end

      field(field_name, config.merge(options))
    end
  end
end

#fields_in_group(group_name) ⇒ Object



78
79
80
81
82
83
84
# File 'lib/subroutine/fields.rb', line 78

def fields_in_group(group_name)
  field_configurations.each_with_object({}) do |(field_name, config), h|
    next unless config.in_group?(group_name)

    h[field_name] = config
  end
end

#get_field_config(field_name) ⇒ Object



86
87
88
# File 'lib/subroutine/fields.rb', line 86

def get_field_config(field_name)
  field_configurations[field_name.to_sym]
end

#respond_to_missing?(method_name, *args, &block) ⇒ Boolean

Returns:

  • (Boolean)


90
91
92
# File 'lib/subroutine/fields.rb', line 90

def respond_to_missing?(method_name, *args, &block)
  ::Subroutine::TypeCaster.casters.key?(method_name.to_sym) || super
end