module Form
module Component
class Base
extend Forwardable
def_delegators :form, :data
# The +Form::Builder+ instance. It will provide the base name
# and data object.
#
attr_accessor :form
# The input name. It will be used to compose
# the full name.
#
attr_accessor :name
# Hold the input options. It will be used as the input's
# attributes.
#
attr_accessor :options
# Initialize the component and set some variables.
#
def initialize(form, name, options = {})
@form = form
@name = name
@options = options
end
# Retrieve the value from the form data.
#
def value
if data.respond_to?(name)
data.public_send(name)
elsif data.respond_to?(:[])
data[name.to_sym] || data[name.to_s]
end
end
# Return a composed name like user[profile][twitter].
#
def composed_name
composed_name = [form.base_name, name].flatten.compact
"#{composed_name.shift}" + composed_name.map {|n| "[#{n}]"}.join("")
end
# Just pass all arguments to I18n.t.
#
def t(*args)
I18n.t(*args)
end
#
#
def humanize(name)
parts = name.to_s.split("_")
parts.first.gsub!(/\A(.)/) { $1.upcase }
parts.join(" ")
end
#
#
def id_attribute
[form.base_name, name].flatten.compact.join("-")
end
end
end
end