Created
February 21, 2013 22:59
-
-
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.
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
module Services | |
class LoadsPositionTypes | |
extend ::Services::LookupDataFetchable | |
def self.entity_class | |
PositionType | |
end | |
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
module Services | |
class LoadsStates | |
extend ::Services::LookupDataFetchable | |
def self.entity_class | |
State | |
end | |
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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I would consider calling "to_class" "constantize" just to make Rails developers feel more at home :)