Skip to content

Instantly share code, notes, and snippets.

@adomokos
Created February 21, 2013 22:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adomokos/5009226 to your computer and use it in GitHub Desktop.
Save adomokos/5009226 to your computer and use it in GitHub Desktop.
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

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

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