Class: DynamicFields::Field

Inherits:
Object
  • Object
show all
Defined in:
lib/dynamic_fields/field.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, options = {}) ⇒ Field

Create the new field with a name and optional additional options. Valid options are :default

Options:

name: The name of the field as a Symbol. options: A Hash of options for the field.

Example:

Field.new(:score, :default => 0)



15
16
17
18
19
# File 'lib/dynamic_fields/field.rb', line 15

def initialize(name, options = {})
  @name, @default = name, options.delete(:default)
  @type = options.delete(:type) || :string
  @options = options
end

Instance Attribute Details

#defaultObject (readonly)

Returns the value of attribute default.



3
4
5
# File 'lib/dynamic_fields/field.rb', line 3

def default
  @default
end

#nameObject (readonly)

Returns the value of attribute name.



3
4
5
# File 'lib/dynamic_fields/field.rb', line 3

def name
  @name
end

#optionsObject (readonly)

Returns the value of attribute options.



3
4
5
# File 'lib/dynamic_fields/field.rb', line 3

def options
  @options
end

#typeObject (readonly)

Returns the value of attribute type.



3
4
5
# File 'lib/dynamic_fields/field.rb', line 3

def type
  @type
end

#type_classObject (readonly)

Returns the value of attribute type_class.



3
4
5
# File 'lib/dynamic_fields/field.rb', line 3

def type_class
  @type_class
end

Instance Method Details

#has_default?Boolean

Returns:

  • (Boolean)


25
26
27
# File 'lib/dynamic_fields/field.rb', line 25

def has_default?
  default.present? || default == false || default == ''
end

#migration_string_for(table_state, action) ⇒ Object



29
30
31
32
33
34
35
36
37
38
# File 'lib/dynamic_fields/field.rb', line 29

def migration_string_for table_state, action
  args = [name.to_sym.inspect]
  if action.to_sym == :add
    args << type.inspect if table_state.to_sym == :update
    args += options_with_default.map do |k, v|
      "#{k.to_sym.inspect} => #{v.inspect}"
    end
  end
  args.join(', ').gsub('\\', '')
end

#options_with_defaultObject



21
22
23
# File 'lib/dynamic_fields/field.rb', line 21

def options_with_default
  has_default? ? options.merge(:default => default) : options
end