Module: FormAttribute

Defined in:
lib/form_attribute.rb,
lib/form_attribute/version.rb

Defined Under Namespace

Modules: InstanceMethods

Constant Summary collapse

VERSION =
'1.0.2'

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(base) ⇒ Object



7
8
9
10
11
12
13
# File 'lib/form_attribute.rb', line 7

def self.extended(base)
  base.instance_variable_set('@attrs', {})
  base.include InstanceMethods
  base.define_method('initialize') do |**attributes|
    write_many(**attributes)
  end
end

Instance Method Details

#attribute(name, type, options = {}) ⇒ Object



15
16
17
18
19
20
21
22
23
24
# File 'lib/form_attribute.rb', line 15

def attribute(name, type, options = {})
  name = name.to_sym
  default = options[:default]

  init_attribute(name, type, default)

  matching_type_for(name, default)

  define_accessors(name)
end

#attributesObject



26
27
28
# File 'lib/form_attribute.rb', line 26

def attributes
  @attrs.keys
end

#default_for(name) ⇒ Object



34
35
36
# File 'lib/form_attribute.rb', line 34

def default_for(name)
  attr(name)[:default]
end

#matching_type_for(name, value) ⇒ Object

Raises:

  • (TypeError)


38
39
40
41
42
43
44
45
# File 'lib/form_attribute.rb', line 38

def matching_type_for(name, value)
  return true if value.nil?

  type_of(name).each do |type|
    return true if value.is_a? type
  end
  raise TypeError, "#{value.inspect} for #{name.inspect} is the wrong type"
end

#type_of(name) ⇒ Object



30
31
32
# File 'lib/form_attribute.rb', line 30

def type_of(name)
  attr(name)[:type]
end