Display inactive record objects to JSON / XML [RoR]
I am testing a small whois API using the ruby ββwhois gem, and because the whois response format is quite funny, I was sometimes asked not to use ActiveRecord to save responses.
Simply put, this is how it works:
- User enters domain name in form from view (action 'lookup' = create request)
- The controller catches this parameter, then sends it to the model (non activerecord), initiating the request object [containing the whois response]
- The model uses the whois gem and sends back the whois response to the controller
- The controller sends the response in different formats (html / json / xml), but only the html object receives the object.
Here is the code for the "search" action for my "requests" controller:
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 it, it keeps spilling nilClass exceptions.
So, when I go to localhost:8080/requests/lookup
, everything displays 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 to give instructions in the builders (Jbuilder / XMLBuilder) it throws a nilClass exception, proving that the variable scope is not so global ...
And no, I don't think including a variable in the session is a good idea: I will only use it for one request.
If necessary, I'll be happy to provide more of my own code if it helps you understand my problem. I know AR is the way to go, but nevertheless I'm curious to know how to get around it for situations like this.
Thank!
source to share
You can use ActiveModel even if you are not using ActiveRecord. Rails 4 made this very easy. You can also add ActiveModel :: Serialization which allows you to serialize objects using .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 names (maybe @result?), you are bound to run into problems and confusion with ActionDispatch::Request
.
source to share