Module: NForm::Attributes

Included in:
Form
Defined in:
lib/nform/attributes.rb

Defined Under Namespace

Modules: InstanceMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(base) ⇒ Object



57
58
59
# File 'lib/nform/attributes.rb', line 57

def self.extended(base)
  base.include(InstanceMethods)
end

Instance Method Details

#__undef_attrObject



21
22
23
# File 'lib/nform/attributes.rb', line 21

def __undef_attr
  @undef_attr ||= :raise
end

#attribute(name, coerce: nil, required: false, default: nil) ⇒ Object



6
7
8
# File 'lib/nform/attributes.rb', line 6

def attribute(name,coerce:nil,required:false,default:nil)
  attribute_set[name.to_sym] = {coerce: coerce, required: required, default: default}
end

#attribute_setObject



10
11
12
# File 'lib/nform/attributes.rb', line 10

def attribute_set
  @attribute_set ||= {}
end

#define_attributesObject



25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/nform/attributes.rb', line 25

def define_attributes
  attribute_set.each do |name,options|
    define_method(name) do
      instance_variable_get("@#{name}")
    end

    # TODO: must use coercion set
    c = get_coercion(options[:coerce])
    define_method("#{name}=") do |input|
      instance_variable_set("@#{name}", c.call(input,self))
    end
  end
end

#get_coercion(coerce_option) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/nform/attributes.rb', line 39

def get_coercion(coerce_option)
  case
  when coerce_option.nil?
    proc{|n| n }
  when coerce_option.is_a?(Symbol)
    NForm::Coercions.fetch(coerce_option)
  when coerce_option.respond_to?(:call)
    coerce_option
  when coerce_option.is_a?(Enumerable)
    chain = coerce_option.map{|o| get_coercion(o) }
    proc do |input,scope|
      chain.reduce(input){|i,c| c.call(i,scope) }
    end
  else
    raise Error, "Invalid coerce option given"
  end
end

#undefined_attributes(option) ⇒ Object



14
15
16
17
18
19
# File 'lib/nform/attributes.rb', line 14

def undefined_attributes(option)
  unless i|raise ignore|.include?(option)
    raise ArgumentError, "Unknown option `#{option}` for undefined attributes. Options are :raise or :ignore"
  end
  @undef_attr = option
end