Class: Id::Model::Field

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

Direct Known Subclasses

Form::FieldWithFormSupport, Association

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model, name, options) ⇒ Field

Returns a new instance of Field.



5
6
7
8
9
# File 'lib/id/model/field.rb', line 5

def initialize(model, name, options)
  @model = model
  @name = name
  @options = options
end

Instance Attribute Details

#modelObject (readonly)

Returns the value of attribute model.



57
58
59
# File 'lib/id/model/field.rb', line 57

def model
  @model
end

#nameObject (readonly)

Returns the value of attribute name.



57
58
59
# File 'lib/id/model/field.rb', line 57

def name
  @name
end

#optionsObject (readonly)

Returns the value of attribute options.



57
58
59
# File 'lib/id/model/field.rb', line 57

def options
  @options
end

Instance Method Details

#cast(value) ⇒ Object



29
30
31
# File 'lib/id/model/field.rb', line 29

def cast(value)
  TypeCasts.cast(options.fetch(:type, false), value)
end

#defaultObject



48
49
50
# File 'lib/id/model/field.rb', line 48

def default
  options.fetch(:default)
end

#default?Boolean

Returns:

  • (Boolean)


44
45
46
# File 'lib/id/model/field.rb', line 44

def default?
  options.has_key?(:default)
end

#default_valueObject



37
38
39
40
41
42
# File 'lib/id/model/field.rb', line 37

def default_value
  proc do
    if default? then default
    elsif !optional? then raise MissingAttributeError, key end
  end
end

#defineObject



11
12
13
14
15
# File 'lib/id/model/field.rb', line 11

def define
  Definer.method_memoize(model, name) { |data| value_of(data) }
  Definer.method(model, "#{name}?") { |obj| presence_of(obj.data) }
  hook_define
end

#hook_defineObject



17
18
# File 'lib/id/model/field.rb', line 17

def hook_define
end

#keyObject



33
34
35
# File 'lib/id/model/field.rb', line 33

def key
  options.fetch(:key, name).to_s
end

#optional?Boolean Also known as: optional

Returns:

  • (Boolean)


52
53
54
# File 'lib/id/model/field.rb', line 52

def optional?
  options.fetch(:optional, false)
end

#presence_of(data) ⇒ Object



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

def presence_of(data)
  data.has_key?(key) && !data.fetch(key).nil?
end

#value_of(data) ⇒ Object



20
21
22
23
# File 'lib/id/model/field.rb', line 20

def value_of(data)
  value = data.fetch(key, &default_value)
  optional ? Option[value].map{ |d| cast d } : cast(value)
end