问题
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 :
- User inputs a domain name in a form from a view (action 'lookup' = creating a request)
- Controller catches the parameter then sends to model (non activerecord) by instanciating the request object [containing the whois response]
- Model uses the whois gem and sends back to controller the whois response
- 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