Render non-activerecord objects in JSON/XML [RoR]

扶醉桌前 提交于 2019-12-13 14:40:15

问题


I am testing a small whois API using the ruby gem whois, and due to the format of whois responses being quite funny sometimes i was asked not to use ActiveRecord for saving the responses.

Simply put, here's how it works :

  1. User inputs a domain name in a form from a view (action 'lookup' = creating a request)
  2. Controller catches the parameter then sends to model (non activerecord) by instanciating the request object [containing the whois response]
  3. Model uses the whois gem and sends back to controller the whois response
  4. Controller sends a response in different formats (html/json/xml) but only html gets the object.

Here is the code for the action "lookup" of my controller "requests" :

def lookup
domain = params[:domain]
@request = Request.new.search(domain)

respond_to do |format|
  if @request != nil
    format.html
    format.json { render :json => @request}
    format.xml {render :xml => @request}
  else
    format.html { render :new }
    format.json { render json: @request.errors, status: :unprocessable_entity }
  end
end

Obviously, i'm having a hard time because i'm not using ActiveRecord, and since RoR is expecting one he keeps spitting nilClass exceptions.

So when i go on localhost:8080/requests/lookup everything is displayed fine, and @request contains all the data i want. But wether localhost:8080/requests/lookup.json or localhost:8080/requests/lookup.xml nothing shows up and if I try giving instructions in the builders (Jbuilder/XMLBuilder) it throws a nilClass exception, proving that the variable scope isn't so global...

And no, i don't think putting in the variable session is a good idea : I will only be using it for a single query.

If needed, i'll be happy to provide more of my code if it may help you understand my problem. I know AR is the way to go, but nonetheless i am curious as to know how to get around it for situations such as this one.

Thank you !


回答1:


You can use ActiveModel even though you are not using ActiveRecord. Rails 4 made it really easy. You can also add ActiveModel::Serialization which allows you to serialize the objects with .to_json and .to_xml

class WhoisLookup
  include ActiveModel::Model
  include ActiveModel::Serializers::JSON
  include ActiveModel::Serializers::Xml

  attr_accessor :search_term # ...

  # you can use all the ActiveModel goodies
  validates :search_term, presence: true, length: {in:2..255}
end

ActiveModel::Serialization will allow you to use:

format.json { render :json => @result } # calls @result.to_json

PS. don´t use @request for variable naming (@result maybe?) you´re bound to run into issues and confusion with ActionDispatch::Request.



来源:https://stackoverflow.com/questions/26806564/render-non-activerecord-objects-in-json-xml-ror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!