Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

move sunlight_api logic into its own class #6

Open
nathanallen opened this issue Jul 22, 2015 · 0 comments
Open

move sunlight_api logic into its own class #6

nathanallen opened this issue Jul 22, 2015 · 0 comments

Comments

@nathanallen
Copy link

But wait! Now that you've moved database logic out of your controller, how are you going to keep your data fresh? How are you going to know when to hit your database vs. the api?

There's a lot going on in politicians_controller.rb:

  • complex queries --> model logic
  • data filtering --> model logic
  • api calls --> where does this go!?

One of the cool things you figured out is that you can send of api requests form the backend.

In your PoliticanController you said:

    include HTTParty
    base_uri("http://transparencydata.com/api/1.0/contributions.json")

Then, elsewhere you slipped in this sneaky line of code (welcome_controller.rb#L24, politicians_controller.rb#L218):

       response = self.class.get("", query)

Holy indirection batman, what's going on!

First of all, it's in a private method, secondly the method is named sunlight_api... That's pretty descriptive. It seems to me we've got ourselves a contender for a new class: SunlightApi. It has one responsibility: fetch the data!

We should be able to configure it with information like:

  • base endpoint
  • api token
  • default parameters

We should then be able to ask it things like:

SunlightApi.get(query) # returns JSON

Now, how do we get the response data into our database? When and where do we use the SunlightApi class? I think I would approach this from the standpoint of your models. We ask your model for data. It either has it or it doesn't. It's either fresh data or it's not. Depending on these conditions, it either hits the database or the api. You used this approach in your check_database method in your controller. What if this kind of conditional logic lived in your model? Your model already knows about the database, why can't it also know about the api?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant