ruby on rails - Render non-activerecord objects in JSON/XML [RoR] -
i testing little whois api using ruby gem whois, , due format of whois responses beingness quite funny asked not utilize activerecord saving responses.
simply put, here's how works :
user inputs domain name in form view (action 'lookup' = creating request) controller catches parameter sends model (non activerecord) instanciating request object [containing whois response] model uses whois gem , sends controller whois response controller sends response in different formats (html/json/xml) html gets object.here code action "lookup" of controller "requests" :
def lookup domain = params[:domain] @request = request.new.search(domain) respond_to |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 hard time because i'm not using activerecord, , since ror expecting 1 keeps spitting nilclass exceptions.
so when go on localhost:8080/requests/lookup
displayed fine, , @request contains info want. wether localhost:8080/requests/lookup.json
or localhost:8080/requests/lookup.xml
nil shows , if seek giving instructions in builders (jbuilder/xmlbuilder) throws nilclass exception, proving variable scope isn't global...
and no, don't think putting in variable session thought : using single query.
if needed, i'll happy provide more of code if may help understand problem. know ar way go, nonetheless curious know how around situations such one.
thank !
you can utilize activemodel though not using activerecord. rails 4 made easy. can add together activemodel::serialization allows serialize objects .to_json
, .to_xml
class whoislookup include activemodel::model include activemodel::serializers::json include activemodel::serializers::xml attr_accessor :search_term # ... # can utilize activemodel goodies validates :search_term, presence: true, length: {in:2..255} end
activemodel::serialization allow use:
format.json { render :json => @result } # calls @result.to_json
ps. don´t utilize @request
variable naming (@result maybe?) you´re bound run issues , confusion actiondispatch::request
.
ruby-on-rails ruby json activerecord
No comments:
Post a Comment