开发者

creating an object from a post request in ruby

This question is about 2 rails apps I'm building. I'm trying to get my head around Rails and restful web services. Most of the code is pseudo but If required I suppose i could attempt some examples.

There are also 开发者_开发百科a few basic rails and web requests thrown in.

Imagine I have rails programs A and B. I want A to send a post request which will basically contain an object formatted in JSON (not required but planned) and B to recieve it and turn it into the object I want. So heres my plan or concept at least and I'd love some feedback on it.

So focusing on B for the moment.

A url like this

127.0.0.1:8080/receive

would link to something like

def recieve (assuming routes are setup correctly)


@object = (this is where im a bit lost. how do i receive it from URL)
@request = UserRequest.new(params[:request])

A lot of tutorials seem to focusing on sending post requests but never receiving or processing them. anyone point me in the right direction?


And for A

I know how to send a post request

 @stringParams = 'www.stackoverflow.com'
    @hostURL = 'http://127.0.0.1:20000/requests/add'
    #This is a post request that needs to post json to my recieveing crawler
    res = Net::HTTP.post_form(URI.parse(@hostURL),
    {'url' =>  @stringParams})
    #puts res.body

I know how to create a JSON object from a hash

 @myHash = HASH.new
    @myHash =
    {
      "url" => 'www.stackoverflow.com'
       #Assume theres more than one variable
    }

@myJsonHash = @myHash.to_json

So the question for A is how do I send that @myJsonHash in a post request. Or is that something thats really stupid to do and have I misunderstood the requirments?


You'll receive data in the parameters. You should know which params contain what.

def receive
  @object = Object.new({:name => params[:name], :address => params[:address] })
  if @object.save
    #ok
  else
    #error
  end
end

Beware of cross sites posts, you should implement some sort of authentication.


between application A and application B there is a layer of communication: HTTP

HTTP defines request types one of which is POST

when POST request hits your rails application - all POSTed data will be accessible through params method within your controllers

it's better to start with explaining how A application should send post request

take a look at this gem: httparty

allows you to send all kinds of requests with minimum amount of code:

class BParty
  include HTTParty

  base 'http://b'

  def self.pass(object)
    post('/receive', :body => {:object => object.to_json})
  end
end

doing post requests to B application is now as simple as

BParty.pass(object)      

that's it. now on application B side you will only have to do this:

@object = JSON.decode(params[:object])

hope that helps, don't kick me if i made typos - all the code from head without testing

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜