Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
DRY-ing up service logic with mixins. Since these services are very similar in behavior I used a "template" method that uses only one dynamic data: the entity type they are fetching.
module Services
class LoadsPositionTypes
extend ::Services::LookupDataFetchable
def self.entity_class
PositionType
end
end
end
module Services
class LoadsStates
extend ::Services::LookupDataFetchable
def self.entity_class
State
end
end
end
module Services
module LookupDataFetchable
def entity_class
raise NotImplementedError.new("You must implement the class method `entity_class`")
end
def from_api(current_user)
service = Object::const_get("Services").const_get("Api").const_get(entity_class.to_s.pluralize) \
.new(current_user.email, current_user.password)
data_json_array = Rails.cache.fetch(entity_class.to_s.downcase.to_sym) do
service.index.fetch("entries")
end
data_json_array.map do |e|
entity_class.new(e)
end
end
end
end
@leviwilson
Copy link

leviwilson commented Feb 21, 2013

class String
  def to_class
    self.split("::").reduce(Object) { |o, part| o.const_get part }
  end
end

Then line 8 becomes:

service = "Services::Api::#{entity_class.to_s.pluralize}".to_class.new(current_user.email, current_user.password)

Not much of an improvement, but I like to extend String to do that 😄

@joefiorini
Copy link

joefiorini commented Feb 22, 2013

I would consider calling "to_class" "constantize" just to make Rails developers feel more at home :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment