Render Dynamic Variables in JSON Feed with Ruby on Rails

I am just looking at creating an API for our clients to interact with our main Rails 3 application.

On the one hand, I wanted the json response to contain some form. Basically, the code of some form, which we control and display on their website.

This works fine for me (simplified):

def login_form @response = Form.find_by_something(params[:something_else]) if @response render :status=>200, :json=>{:response => @response} end end 

And on the client side, I can get:

 @logins = HTTParty.get("#{set_auth_url}/api/v1/logins.json?auth_token=xyz&something_else=abc").parsed_response 

And display the form

 = @logins["response"].html_safe 

The problem is that the form code has some dynamic variables:

For instance:

 <div class="login"> <FORM name="form1" METHOD="get" action="<%= request.path %>?"> <INPUT TYPE="HIDDEN" NAME="chal" VALUE="<%= params['challenge'] %>"> <% if @current_location['success_url'] %> <INPUT TYPE="HIDDEN" NAME="userurl" VALUE="/success"> <% end %> <input type="hidden" name="UserName" placeholder="Username" value="<%= @user['username']['username'] %>"> <input type="submit" name="login" value="Login" class="btn"> </div> 

I wonder is this a good idea? And if so, how can I break these variables in html ??

If this is not the case, someone could recommend a more convenient way to do it.

+4
source share
2 answers

Why not use the Javascript Template for this, as in a jQuery template, mustache or pen

so save the client side form like this

I will describe it with the help of a Mustache ....

 ... <script id="template" type="text/template"> <div class="login"> <FORM name="form1" METHOD="get" action={{request_path}}> <INPUT TYPE="HIDDEN" NAME="chal" VALUE={{challenges}}> {{boolean_value}} <INPUT TYPE="HIDDEN" NAME="userurl" VALUE="/success"> {{/boolean_value}} <input type="hidden" name="UserName" placeholder="Username" value={{user_name}}> <input type="submit" name="login" value="Login" class="btn"> </div> </script> </html> 

The next part gets an ajax response

Using any Javascript Framework I assume this can be achieved I use jQuery here

 <script type="text/javascript"> $(document).ready(function() { $.ajax({ // make ajax call over here success: function(data) { // JSON DATA var template = $('script#template').html(); $([container where html is place]).html(Mustache.to_html(template,data)); } }) }) 

Hope for this help

You donโ€™t know how you would like, although a simple form html tag started with form_tag, because it does not contain an authentication token.

Hope for this help

+1
source

Do these server-side variables know when preparing a response? In this case, I would try to run them using the templating engine template :json=> { :response => ERB.new(@response).result(binding) } - the client would get only html, applicable in his case.

+1
source

Source: https://habr.com/ru/post/1438506/


All Articles