module FormAttribute

Constants

VERSION

Public Class Methods

extended(base) click to toggle source
# 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

Public Instance Methods

attribute(name, type, options = {}) click to toggle source
# 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
attributes() click to toggle source
# File lib/form_attribute.rb, line 26
def attributes
  @attrs.keys
end
default_for(name) click to toggle source
# File lib/form_attribute.rb, line 34
def default_for(name)
  attr(name)[:default]
end
matching_type_for(name, value) click to toggle source
# 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) click to toggle source
# File lib/form_attribute.rb, line 30
def type_of(name)
  attr(name)[:type]
end

Private Instance Methods

attr(name) click to toggle source
# File lib/form_attribute.rb, line 61
def attr(name)
  attribute = @attrs[name]
  return attribute if attribute

  raise UnknownAttributeName, name.inspect
end
define_accessors(name) click to toggle source
# File lib/form_attribute.rb, line 56
def define_accessors(name)
  define_method("#{name}=") { |value| write_attribute(name, value) }
  define_method(name) { read_attribute(name) }
end
init_attribute(name, type, default) click to toggle source
# File lib/form_attribute.rb, line 49
def init_attribute(name, type, default)
  @attrs[name] = {
    type: [type].flatten,
    default: default
  }
end