ActiveResource, how to get a resource from a REST API that has a unique name?

I am trying to grab data from a third-party library that has an API that looks like this:

https://foo.com/user.json?username=<USERNAME>

I cannot figure out how to get ActiveResource to use "user.json" instead of "users.json". Is it possible?

I got it while working with reactive_resources risk ... is there a way to do this only in pure ActiveResources?

+7
source share
2 answers
 class User < ActiveResource::Base self.element_name = "user" end 

Then you ask how to get one element from a URL that looks like ActiveResource for //foo.com/user.json and not for //foo.com/user/.json

 User.find(:one, :from => "https://foo.com/user.json?username=#{<USERNAME>}" 

Edit in response to comment

Is there a way to do this without having to enter the full request URL every time I want to use find ()?

One way is to define a method in the class for the full URL for you.

 class User < ActiveResource::Base self.element_name = "user" def self.find_by_username(username) find(:one, :from => "https://foo.com/user.json?username=#{username}" end def find self.class.find(:one, :from => "https://foo.com/user.json?username=#{username}" end end 

Another way is to override path_path.

 class User < ActiveResource::Base self.element_name = "user" def self.element_path(id, prefix_options = {}, options = {}) "https://foo.com/user.json?username=#{prefix_options["user_id"]}" end end 

Some will call this patch for monkeys, others will call it object-oriented programming. I say this is only switching to monkeys when you go into code or use the dynamic nature of Ruby to change the basic behavior, and this is an absolutely legitimate way to do something in object-oriented programming. However, the Ruby community does not use OOP much, almost ignoring inheritance in favor of much weaker (and less well-proven) mixes, and only using duck typing for polymorphism.

The problem of having to interact with ActiveResource to create a URL where you cannot redefine a web service to accept ActiveResource conventions is why many people use HTTParty. "If you need to create a URL, it can also use HTTParty."

+8
source

If you only need to get rid of the pluralization of the resource name in the URL, redefine collection_name :

 class User < ActiveResource::Base self.element_name = "user" def self.collection_name element_name end end 
+2
source

All Articles