Created
September 20, 2012 12:56
-
-
Save markjlorenz/3755725 to your computer and use it in GitHub Desktop.
A Ruby Object that Works Like Javascript's Objects. The idea is to make creating/validating non-model based forms easier.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AssociativeObject | |
def eigenclass; class << self; self; end; end | |
#form_for requires these methods | |
attr_accessor :id | |
attr_accessor :errors | |
def new_record?; return true; end | |
def to_param; return nil; end #for AR object to_param returns nil for new objects | |
def to_key; id ? [id] : nil end #borrowed from rails source for dummy object | |
def self.model_name; ActiveModel::Name.new(self); end #how AR determines the name for the params hash. TODO: allow dynamic assignment | |
def initialize hash={} | |
return unless hash #incase nil is passed | |
hash.each do |name, value| | |
add_association name, value | |
end | |
end | |
def []= key, value | |
add_association key, value | |
end | |
def [] key | |
respond_to?(key.to_sym) ? send(key.to_sym) : nil | |
end | |
protected | |
def add_association name, value | |
eigenclass.send :attr_accessor, name.to_sym | |
send (name.to_s+"=").to_sym, value | |
eigenclass.send :public, name.to_sym #else the accessor will be protected too | |
eigenclass.send :public, (name.to_s+"=").to_sym | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def by_department | |
@a_object = AssociativeObject.new params[:associative_object] | |
@a_object[:from] ||= Date.today - 2.months | |
@a_object[:to] ||= Date.today | |
@a_object[:department_id] ||= 2 #default to PS R&D | |
@results = SomeModel.find_by_department_from_and_to @a_object.department_id, @a_object.from, @a_object.to | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%= form_for @a_object, url:some_model_path do |f| %> | |
<%= f.collection_select :department_id, Department.all, :id, :name %> | |
<%= f.text_field :from, class:"date" %> | |
<%= f.text_field :to, class:"date" %> | |
<%= f.submit "Search" %> | |
<% end %> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment