module NForm::Attributes

Public Class Methods

extended(base) click to toggle source
# File lib/nform/attributes.rb, line 70
def self.extended(base)
  base.include(InstanceMethods)
end

Public Instance Methods

__hash_rep() click to toggle source
# File lib/nform/attributes.rb, line 33
def __hash_rep
  @hash_rep ||= :complete
end
__undef_attr() click to toggle source
# File lib/nform/attributes.rb, line 29
def __undef_attr
  @undef_attr ||= :raise
end
attribute(name,coerce:nil,required:false,default:nil) click to toggle source
# File lib/nform/attributes.rb, line 7
def attribute(name,coerce:nil,required:false,default:nil)
  attribute_set[name.to_sym] = {coerce: coerce, required: required, default: default}
end
attribute_set() click to toggle source
# File lib/nform/attributes.rb, line 11
def attribute_set
  @attribute_set ||= {}
end
define_attributes() click to toggle source
# File lib/nform/attributes.rb, line 37
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|
      @__touched_keys << name
      instance_variable_set("@#{name}", c.call(input,self))
    end
  end
end
get_coercion(coerce_option) click to toggle source
# File lib/nform/attributes.rb, line 52
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
hash_representation(option) click to toggle source
# File lib/nform/attributes.rb, line 22
def hash_representation(option)
  unless %i|partial complete|.include?(option)
    raise ArgumentError, "Unknown option `#{option}` for hash representation. Options are :partial or :complete"
  end
  @hash_rep = option
end
undefined_attributes(option) click to toggle source
# File lib/nform/attributes.rb, line 15
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