Module: CustomFields::Types::Default::Target::ClassMethods

Defined in:
lib/custom_fields/types/default.rb

Instance Method Summary collapse

Instance Method Details

#apply_custom_field(klass, rule) ⇒ Object

Modify the target class according to the rule. By default, it declares the field and a validator if specified by the rule

Parameters:

  • klass (Class)

    The class to modify

  • rule (Hash)

    It contains the name of the field and if it is required or not



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/custom_fields/types/default.rb', line 44

def apply_custom_field(klass, rule)
  klass.field rule['name'], localize: rule['localized'] || false, default: rule['default']

  klass.validates_presence_of rule['name'] if rule['required']

  return unless rule['unique']

  klass.validates_uniqueness_of rule['name'],
                                scope: :_type,
                                allow_blank: !rule['required']
end

#default_attribute_get(instance, name) ⇒ Hash

Build a hash storing the formatted (or not) values for a custom field of an instance. Since aliases are accepted, we return a hash. Beside, it is more convenient to use (ex: API). By default, it only returns hash with only one entry whose key is the second parameter and the value the value of the field in the instance given in first parameter.

Parameters:

  • instance (Object)

    An instance of the class enhanced by the custom_fields

  • name (String)

    The name of the custom field

Returns:

  • (Hash)

    field name => formatted value or empty hash if no value



69
70
71
72
73
74
75
# File 'lib/custom_fields/types/default.rb', line 69

def default_attribute_get(instance, name)
  if (value = instance.send(name.to_sym)).nil?
    {}
  else
    { name => instance.send(name.to_sym) }
  end
end

#default_attribute_set(instance, name, attributes) ⇒ Object

Set the value for the instance and the field specified by the 2 params. Since the value can come from different attributes and other params can modify the instance too, we need to pass a hash instead of a single value.

Parameters:

  • instance (Object)

    An instance of the class enhanced by the custom_fields

  • name (String)

    The name of the custom field

  • attributes (Hash)

    The attributes used to fetch the values



87
88
89
90
91
92
93
# File 'lib/custom_fields/types/default.rb', line 87

def default_attribute_set(instance, name, attributes)
  # do not go further if the name is not one of the attributes keys.
  return unless attributes.key?(name)

  # simple assign
  instance.send(:"#{name}=", attributes[name])
end