Created
February 23, 2013 20:35
-
-
Save elskwid/5021244 to your computer and use it in GitHub Desktop.
Enumerator fun
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
require "active_support/all" | |
class Event | |
STATES = %w(active archived) | |
def self.types(&block) | |
return to_enum(__callee__) unless block | |
types = { | |
entity_address: [ | |
"verified_for_billing", | |
"verified_for_care", | |
"verified_for_records", | |
"verified_for_serve" | |
], | |
order: [ | |
"case_number_empty", | |
"case_number_set" | |
] | |
} | |
types.each do |k, v| | |
v.each do |t| | |
yield k,t | |
end | |
end | |
end | |
def self.types_for(model) | |
model = model.to_s.underscore.to_sym | |
types.select { |k, t| k == model } | |
end | |
types.each do |model, type| | |
define_singleton_method "#{model}_#{type}" do | |
puts "events.event_type = ?", "#{model}.#{type}" | |
end | |
end | |
attr_accessor :item_type | |
def initialize(type=nil) | |
@item_type = type | |
end | |
# Validation options for event type based on item type. | |
def event_type_options | |
event_types = self.class.types_for(item_type) | |
event_types.map { |model, type| "#{model}.#{type}" } | |
end | |
end | |
e = Event.new | |
puts e.event_type_options.inspect | |
# => [] | |
e1 = Event.new("EntityAddress") | |
puts e1.event_type_options.inspect | |
# => ["entity_address.verified_for_billing", "entity_address.verified_for_care", "entity_address.verified_for_records", "entity_address.verified_for_serve"] | |
Event.entity_address_verified_for_billing | |
# => events.event_type = ? | |
# => entity_address.verified_for_billing | |
Event.order_case_number_empty | |
# => events.event_type = ? | |
# => order.case_number_empty |
Good call with define_singleton_method
.
I like what you've done with self.types
, certainly addresses the smell I had in my event_type_options
.
Also, take a look at the Issue model in that project. It's a related example that used arrays to define the types and had a slightly cleaner options method than the Event model called for.
Will do.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'd eventually like to see this kind of thing as an internal class with some meaningful semantics. Types, states, that kind of thing. They show up all the time.