I'm building a practice Web API with Ruby + Sinatra and I want my responses to be displayed in a ERB template with formatted JSON (GeoJSON). So far I've been able to process the request and format the response correctly.
However, I can't find a way to display the contents in the endpoint as a JSON string, and it displays as a regular string (difficult to read for JSON). Is there any way to do that in Ruby + Sinatra without using JavaScript?
Here's what I've got so far in both files.
# app.rb
before do
json = File.open("data/cities.json").read
data = JSON.parse(json)
data.each do |item|
geoarray["features"].append(json_to_geojson(item))
end
#geojson = geoarray.to_json
end
...
get('/myendpoint') do
#activities = #geojson
erb :cities
end
<!--cities.erb-->
<%= #activities %>
try <%= #activities.to_json.html_safe %>
You can make JSON string look prettier by using JSON.pretty_generate() method.
# app.rb
before do
json = File.open("data/cities.json").read
data = JSON.parse(json)
data.each do |item|
geoarray["features"].append(json_to_geojson(item))
end
# use pretty_generate instead of to_json
#geojson = JSON.pretty_generate(geoarray)
end
And In your erb file. Instead of simple showing it, add <pre> tag to it.
<!--cities.erb-->
<pre><%= #activities %></pre>
reference
Related
Rails drive me crazy. I'm trying to respond to with an action with JSON.
My goal is to let be the JSON the only format for a response to a URL.
Let's see some code.
The Model is a Devise user, with some added field.
The Controller is my UsersController that has this action
# /app/controllers/users_controller.rb
def static
render json: current_user
end
I got also this jbuilder view
# /app/views/users/static.json.jbuilder
json.content format_content(#user.content)
json.author do
json.name #user.name
json.email_address #user.email
end
if current_user.admin?
json.someValue "foo"
end
this View doesn't do some interesting stuff, but It's just a try.
Anyway I'll never get the static.json.jbuildercontent. I always get all Devise user's content as a JSON.
Am I doing something wrong? (or better: where I done the epic fail?)
Anyway found the solution:
# /config/route.rb
get 'my-static-json' => 'mycontroller#static', defaults: {format: :json}
# /app/controllers/mycontrollers_controller.rb
def my-static-json
end
# /app/views/mycontrollers/my-static-json.json.jbuolder
json.content "some static content"
this is only an example but gives have all the information that I needed
I've been able to set all of my content types to be JSON in a before block, but is there a sinatra after filter that allows me to run to_json on all of the responses (instead of writing to_json 3 times in my example below)?
require 'sinatra'
require 'json'
before do
content_type :json
end
get '/' do
{ song: "Hello" }.to_json
end
get '/go' do
{ song: "Go Yo Ho" }.to_json
end
get '/hi' do
{ song: "Wake me Up" }.to_json
end
Thanks!
You can do that in an after block:
before do
content_type :json
end
get '/' do
{ a: 1 }
end
after do
response.body = JSON.dump(response.body)
end
Sinatra will re-calculate the correct content length for the updated body value.
An alternate way would be to use a helper:
helper do
def j(data)
JSON.dump(data)
end
end
get '/' do
j({ a: 1 })
end
The Sinatra::JSON project does the same thing. Also, you might want to look at libraries designed for building APIs like Grape or Goliath. These two libraries provide a easy way to attach decoders and encoders to handle this type of automatic conversion.
Put set :default_content_type, 'application/json' and all your responses will include a Content-Type: application/json header.
This is what I thought a very simple issue. Basically I am trying to send a json string to a REST API service. Here is the JSON they supply
"vslText": "[field1] = '12345678'"
Now to send it to the REST as a string I've tried
String jsonRequest = "{ 'vslText' : '[field1] = " + ""
But I get lost in all the quotes.
I tried using
JSONObject jsonRequest = new JSONObject();
jsonRequest.put("vslText", "[field1] = '12345678'");
but I get this error
An error occurred at line: 18 in the jsp file: /jsp/javaServlet/IDsearch.jsp
JSONObject cannot be resolved to a type
Here is my import clause
<%# page import="java.util.*" %>
<%# page import= "java.io.*" %>
<%# page import= "java.net.*" %>
<%# page import= "org.json.JSONObject" %>
Please give me direction?
Using eclipse I was able to add the .jar to the list of libraries the web app could see. Basically right click on the project and select build path then configure build path. From there, you can go to the libraries tab and add JARS using the interface.
After re-exporting it as a war file this seemed to work.
On my site I want a form to be rendered based on what type of data the user is inputing. When I call the controller method in my view, it's outputting tons of HTML where the form should be as plain text starting from DOCTYPE to . I'm using a post form that was previous in place statically to try it out.
Controller:
def feed_form(form_type)
form_type = %w{type_1 type_2}.include?(form_type) ? form_type : 'post'
render "_#{form_type}_form"
end
And the view calling the action:
= feed_form 'post'
And the form:
.feed-form
%h3 News Feed
= form_for(#post) do |f|
= render 'shared/error_messages', object: f.object
.field
= f.text_area :content, placeholder: "Make your new post here..."
= f.submit "Post", class: "post-button"
You are don't supposed to call controller methods from a view.
You must prepare all the data for view rendering (e.g. all required models) in controller method, and put it into #variables.
And then in view you write all your html using already prepared #variables, you can call helpers methods from a view, but not controller's.
Try to put your def feed_form(form_type) code into a helper.
P.S.: and read something about MVC architecture.
I want an external webpage rates.appiclife.com to be rendered in the applications <%=yield%>.
I tried this:
I placed the following method in pages_controller.rb
def fetch_url(url)
r = Net::HTTP.get_response( URI.parse( url ) )
if r.is_a? Net::HTTPSuccess
r.body
else
nil
end
end
In the same file:
def showexternal
#snippet = fetch_url "http://rates.appiclife.com/"
end
And in the showexternal.html.erb view/pages:
<%= #snippet %>
I get the following error: incompatible character encodings: UTF-8 and ASCII-8BIT
Is it even possible to do this? The thing is that those prices are updated and received in an excel file, so a lot of work to adapt them if I just place them in a html-table.
You should be able to parse the request response with Nokogiri into a string and then do whatever you want to with it. You can find a quick tutorial here:
http://nokogiri.org/tutorials/parsing_an_html_xml_document.html