module Crystal class ModelHelper attr_accessor :template, :model_name, :model, :options, :form_helper def initialize template, form_helper, model_name, model, options self.template, self.form_helper, self.model_name, self.model, self.options = template, form_helper, model_name, model, options end # # Helpers # def check_box name, options = {} render_attribute name, options do |fname, value, o| form_helper.check_box_tag fname, !!value, o end end def file_field name, options = {} render_attribute name, options do |fname, value, o| form_helper.file_field_tag fname, o end end def hidden_field name, options = {} render_attribute name, options do |fname, value, o| form_helper.hidden_field_tag fname, value, o end end def password_field name, options = {} render_attribute name, options do |fname, value, o| form_helper.password_field_tag fname, nil, o end end def radio_button name, options = {} render_attribute name, options do |fname, value, o| form_helper.radio_button_tag fname, !!value, o end end def submit value, options = {} form_helper.submit_tag value, options end def text_field name, options = {} render_attribute name, options do |fname, value, o| form_helper.text_field_tag fname, value, o end end def text_area name, options = {} render_attribute name, options do |fname, value, o| form_helper.text_area_tag fname, value, o end end def error_messages merrors = errors['base'] form_helper.error_messages merrors.to_a unless merrors.blank? end protected def method_missing m, *args, &b form_helper.send m, *args, &b end def render_attribute name, options, &block name = name.to_s ferrors = errors_for(name) if form_helper.respond_to? :field_with_errors field_html = block.call field_name_for(name), value_of(name), options unless ferrors.blank? form_helper.field_with_errors name, ferrors, options, field_html else field_html end else options['errors'] = ferrors block.call field_name_for(name), value_of(name), options end end def errors unless @errors @errors = {} ( (model.respond_to?(:errors) && model.errors) || (model.respond_to?(:[]) && (model['errors'] || model[:errors])) || {} ).each do |k, v| @errors[k.to_s] = v end end @errors end def errors_for name errors[name].to_a end def field_name_for name "#{model_name}[#{name}]" end def value_of name if model.respond_to? name model.send name elsif model.respond_to? :[] model[name.to_s] || model[name.to_sym] else raise "Model not respond to :#{name} nor to :[]!" end end end end