Sinatra Success Stories

Sinatra success stories

I've dabbled with Sinatra, but haven't really written anything serious with it.
As you said above, there's a list at http://www.sinatrarb.com/wild.html, although a lot of the applications listed there seem to link to GitHub pages, which I assume are often people experimenting with Sinatra and publishing their results online. Then, there's also the Sinatra mailing list, where you might find links to some interesting projects.[*]

As for your question on when to use Sinatra, I personally would answer "for smaller projects." When you want something up and running very quickly, it seems like Sinatra is an excellent choice. It's also great for people who like Ruby. With that I mean, when you're doing something in Rails, you have to do it "The Rails Way". Rails is the framework upon which you're building your application, and you have to adhere to its customs and conventions. Sinatra, on the other hand, feels like a library. You feel like you're writing Ruby, if you want to connect to a database, you use the library you like/think is appropriate for the job, if you want to output HTML you choose the templating library you like, and if you want a simple web framework, you choose Sinatra. Sinatra is not something upon which you build your whole application, it's something you use beside the rest of your application.

So, as you may have gathered, I'm quite fond of Sinatra, and I would use it for personal (or small-scale) projects. It's easy to set up and easy to use, as long as you know what you're doing. Looking through http://www.sinatrarb.com/wild.html, it seems like that's what most people are using it for, see for example Is Lost on yet? and Calendar About Nothing.

[*] Edit: I found a thread here, with people linking to their projects. There seem both larger and smaller projects. Very interesting stuff.

Sinatra view doesn't refresh after some delete requests

There is reloading a page and there is redirecting to a page.

When you use the redirect method of Sinatra it responds with a 302 or 303 status code.

# @see https://github.com/sinatra/sinatra/blob/v2.0.0/lib/sinatra/base.rb#L271
# Halt processing and redirect to the URI provided.
def redirect(uri, *args)
if env['HTTP_VERSION'] == 'HTTP/1.1' and env["REQUEST_METHOD"] != 'GET'
status 303
else
status 302
end

# According to RFC 2616 section 14.30, "the field value consists of a
# single absolute URI"
response['Location'] = uri(uri.to_s, settings.absolute_redirects?, settings.prefixed_redirects?)
halt(*args)
end

By calling redirect "/" you are asking the browser to redirect to "/", which would normally trigger a fresh page. However, you're already on that page, so the jQuery code is receiving a redirect and you're asking for a reload via location.reload() upon success. Success is generally indicated by responding with a 2xx code, so I'd posit that the redirect means the success handler isn't firing, and because the browser realises you're already on the page the redirect has asked for it doesn't attempt a redirect either and you end up with no fresh data.

The route should probably look more like this:

delete '/delete/:record_id' do
id = get_record_id
delete_record id
halt 200 # think about handling errors too
end

The success handler should now fire. Moral of the story, be explicit in what you want to do, don't rely on side effects (like a redirect sharing some properties of a reload) to do what you want.

Ruby / Sinatra - Already initialized constant WFKV_

Simple fix: gem 'rack' , '1.3.3' (use the previous version of rack and the error goes away.) Much better than simply silencing.

HAML Pass partial dynamically to layout in Sinatra app

Ah it was so simple afterall.. With the help of this question, I realized now of course that everything is wrapped with layout.haml and I simply needed to place the appopriate yield statement.

layout.haml

!!!
%html
%head
= partial :head
%body
= partial :header
= yield
= partial :footer

And call the template as usual:

get '/test' do    
haml :"test/index"
end

Sinatra - Dashing.io setting timezone

Active Support is not installed by default.

There are two stages of using third-party library's.

  1. Installation
  2. Registration

First things first, I assume that you follow the official guide on dashing.io.

stage 1 - Installation

With this in place you can add the gem activesupport which you need for this in to your Gemfile. Just adding a line like this:

gem 'activesupport'

After that you need to install it, you can do that with just running a second time bundle this fetch all gems and install it.

stage 2 - Registration

After you installed it, you can do what you tried with:

require 'active_support/all'

This tell that you load the active_support library.

THE END

After this two simple steps you can use Time.zone as expected.

How can you get Sinatra to properly process a JSON request that has an array in it?

The first thing you need to understand to solve this problem is that you are currently not sending JSON. JQuery is serializing the data as application/x-www-form-urlencoded, using the param() function, and is sending (it is actually sending the escaped version of this):

cart[0][qty]=1&cart[0][product][name]=baseball&cart[1][qty]=3&cart[1][product][name]=soccer

The documentation for param() has the following pair of notes:

Note: Because some frameworks have limited ability to parse serialized arrays, developers should exercise caution when passing an obj argument that contains objects or arrays nested within another array.

and

Note: Because there is no universally agreed-upon specification for param strings, it is not possible to encode complex data structures using this method in a manner that works ideally across all languages supporting such input. Use JSON format as an alternative for encoding complex data instead.

This is the issue you are facing. Sinatra tries to parse the form-urlencoded data into a Ruby data structure, but it is expecting a different format. It is using Rack::Utils.parse_nested_query which produces the params you are seeing from that query string.

As the jQuery docs suggest, the solution is to send the data as JSON. This will ensure the structure of the data is not mangled between the browser and the server.

The first step is to get the browser to send JSON. You can do this with the other form of the post() function, specifying the content type and converting the data to a JSON string:

$.post({url: "/endpoint", data: JSON.stringify(payload), contentType: "application/json", success: submit});

By default Sinatra will ignore any request with a content type of JSON, and leave the processing to you, so the other half of the solution is to get Sinatra to parse the JSON, and optionally populate the params hash.

One way of doing this to use the Rack contrib module PostBodyContentTypeParser. Simply add the following to your app (you will need to install the rack-contrib gem first):

require 'rack/contrib/post_body_content_type_parser'

use Rack::PostBodyContentTypeParser

Now any POST or PUT request that has a JSON content type will be parsed and the contents added to the params hash. However the current released version doesn’t have and way to convert the keys to symbols (there is a change in master to allow this, but it hasn’t been released yet) so it will produce something like:

{
"cart"=>[
{"qty"=>1, "product"=>{"name"=>"baseball"}},
{"qty"=>3, "product"=>{"name"=>"soccer"}}
]
}

If you want to get symbolized keys you will have to do it “manually”. In your route you can add:

request.body.rewind # Just in case some middleware has already read it
data = JSON.parse(request.body.read, symbolize_names: true)

(You could add this to a before filter if you wanted, just add a check that the content type actually is JSON).

This doesn’t add the data to the params hash, but does give you the data in the form you are looking for.

In ruby with sinatra, How to get I response with get method on rest client?

Method 'get' from the 'RestClient' class return some object with attributes. So response have few values. Which of them do you need? Access to them you can get by their names, its described here.


In your case, after response = RestClient.get get_url... you should have variable response and ability to call response.headers, response.code or response.body.


But im afraid that you have some problems with autorization, which means that imp_uid or token is not correct. Thats why remote server sended to you responce with http-code 401 (Unauthorized). If it is so you should try to check your imp_uid and token. If everything is correct try to reach support of iamport.kr .

Return empty body with Sinatra

Using the Rack interface

From the documentation:

You can return any object that would either be a valid Rack response, Rack body object or HTTP status code:

  • An Array with three elements: [status (Fixnum), headers (Hash), response body (responds to #each)]
  • An Array with two elements: [status (Fixnum), response body (responds to #each)]
  • An object that responds to #each and passes nothing but strings to the given block
  • A Fixnum representing the status code

So returning either of

  1. [200, {}, ['']]
  2. [200, ['']]
  3. ['']
  4. 200

should do the trick.

Using helpers

In Setting Body, Status Code and Headers, the helper methods status and body (and headers) are introduced:

get '/nothing' do
status 200
body ''
end


Related Topics



Leave a reply



Submit