You are here: Blogsphere Longtail

Rails BlogSphere

BlogSphere

Keep up to date with your favourite Rails bloggers in context.

Read more about how it works


Foto%20765x65 RESTful JSONP in Rails using Rack middleware

by Antonio Garrote Hernández | about 1 hour ago | Read more

Rails 2.3 has finally included support for Rack. The Rack project (http://rack.rubyforge.org/) consists of an abstraction layer on top of the webserver that provides a common set of services for developers while hiding the complexity of the web server software whatever it should be (mongrel, glassfish, thin, etc).

The support for Rack is a major accomplishment of the Rail Core Team and opens a lot of interesting new capabilities for the framework users.

In this post entry I will comment a possible use of Rack to provide support for RESTful-like requests for JSONP in Rails.

As you surely know, current desktop browsers only give support for GET and POST HTTP requests. This is a serious difficulty for clients trying to follow REST design guidelines in browser clients, since PUT and DELETE methods are needed to carry request to the server asking for the update and deletion of a resource.

Rails address this problem allowing to pass a '_method' parameter in POST requests that overwrites with its value the POST method of the request. In this way, PUT and DELETE requests can be sent from a HTML form or from an AJAX request.

But this feature only solves half of the problem. Web browsers implement a security model known as the Same Origin Policy (http://en.wikipedia.org/wiki/Same_origin_policy), where only requests to the same domain of the current URL are allowed. This policy effectively forbids cross domain AJAX requests. At least until a common specification for cross domain XMLHTTPRequests can be agreeded and implemented (http://dev.w3.org/2006/webapi/XMLHttpRequest-2/).

One work-around for this problem has been found in the use of JSONP (http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/) a technique where a new SCRIPT tag is inserted into the web page DOM with a callback parameter. The server answers with a script where the callback parameter value is used as a function name that is invoked with the data from the server passed as the actual parameter invokation value.

JSONP, though nothing more than a hack, is been used by many web pages and services to provide data to javascript clients and mashups. A big problem with JSONP appears when you try to use JSONP in a RESTful way. Including the SCRIPT tag in the page initiates a new GET request to the server, so if you wants to use JSONP to send a request for creating a new resource (POST), updating it (PUT), or deleting it (DELETE), you must use some work-around like the use of the _method parameter in Rails. But the overwriting of the HTTP method in Rails only works with POST request: no RESTful JSONP for you my friend.

Of course, you can always try to modify the behaviour of the method override mechanism of Rails with a little bit of monkey patching. Solutions in these direction has been proposed (http://www.actsasflinn.com/2008/06/13/cross-domain-restful-json-p-with-rails) but they are very likely to break with each new Rails release.

With the support for Rack in Rails 2.3 the situation has changed and a cleaner way to change the behavior of MethodOverride in Rails can be built.

Now, MethodOverride is a class of the Rack Rails middleware stack (http://rack.rubyforge.org/doc/classes/Rack/MethodOverride.html). Rack Rails allow developers to insert new middleware classes in the stack (http://guides.rubyonrails.org/rails_on_rack.html), so you can easily add a new middleware before MethodOverride that allows the use of _method parameters with GET requests, without the need of monkey patching:

 module SemanticResource
   
   # Allows overwriting of HTTP method also in
   # GET HTTP requests in order to allow
   # RESTful JSONP calls
   class RestfulJsonpMiddleware
   
     HTTP_METHODS = %w(GET HEAD PUT POST DELETE OPTIONS)
     METHOD_OVERRIDE_PARAM_KEY = "_method".freeze
     HTTP_METHOD_OVERRIDE_HEADER = "HTTP_X_HTTP_METHOD_OVERRIDE".freeze
     
     attr_accessor :method_parameter_name
     
     def initialize(app)
       @app = app
       @method_parameter_name = METHOD_OVERRIDE_PARAM_KEY
     end
 
     # We check if the method parameter is in the request
     # and set up the request to allow the execution of the
     # overwritten HTTP method
     def call(env)
       req = ActionController::Request.new(env)
       method = req.params[@method_parameter_name]
       method = method.to_s.upcase
       if HTTP_METHODS.include?(method)
         env["rack.methodoverride.original_method"] = env["REQUEST_METHOD"]
         env["REQUEST_METHOD"] = "POST"
         env[HTTP_METHOD_OVERRIDE_HEADER] = method
       end
      @app.call(env)
     end
   end
 end
 

And now we can add the middleware in config.rb

 config.middleware.insert_before(Rack::MethodOverride,SemanticResource::RestfulJsonpMiddleware)

That's it, cross domain RESTful AJAX for Rails in a little bit cleaner way! You must take some time to consider the security implications of this change in your application though.

In_the_office_profile Watwet from karim [04/07/2009 16:01]

by Waheed Barghouthi | about 2 hours ago | Read more

@ramsey Wow... They have thought about it... Amazing... btw... I will be in ramallah tomorrow

In_the_office_profile Watwet from ymj [04/07/2009 15:27]

by Waheed Barghouthi | about 2 hours ago | Read more

@karim just click the option key then click on the itunes indicator and you'll have it in hours and days

My120_135 RE: RE: RE: Папку в архив.. как?!

by Ruslan Voloshin | about 3 hours ago | Read more

Вот у меня реализован еще такой вариант
<code:ruby>
def download_client
client_type = params[:id]
if client_type.eql?('php')
file_name = "tmp/ziped_clients/#{current_user.uid}.zip"
FileUtils.remove_file(file_name, true)
=begin
Версия с созданием файла пхп архива.
=end
file = Zip::ZipFile.open(file_name, Zip::ZipFile::CREATE) {
|zipfile|
zipfile.mkdir(current_user.uid.to_s)
zipfile.add("#{current_user.uid}/client.php", "#{RAILS_ROOT}/crawler/client.php")
}
=begin
Версия с созданием пхп архива в через прямую запись в архив.
=end
# Zip::ZipOutputStream::open("my.zip"){ |io|
# io.put_next_entry("#{current_user.uid}/client.php")
# File.open("#{RAILS_ROOT}/crawler/client.php"){|f|
# f.each{|line| io.write line}}
# io
# }
send_file file_name, :size => file.size, :filename => "#{current_user.uid}.zip"
else
render :text => 'Unknown client format!!!'
end
return


zip, ZipFile, ZipOutputStream

My120_135 RE: RE: Разграничение прав доступа

by Ruslan Voloshin | about 3 hours ago | Read more

Если это будет в виде плагина, то интересу будет к нему явно повышен.

My120_135 RE: проблема при использования attachment_fu для аплоада

by Ruslan Voloshin | about 3 hours ago | Read more

К стати форма должная иметь multipart type иначе файлы ты не загружаешь.

In_the_office_profile Watwet from triplem [04/07/2009 15:05]

by Waheed Barghouthi | about 3 hours ago | Read more

RT @AlMasryAlYoum_E: The "N-Word" http://watwet.com/u/06f20d #Egyworkers #Egypt

In_the_office_profile Watwet from mudoveee [04/07/2009 14:40]

by Waheed Barghouthi | about 3 hours ago | Read more

RT @majd_shweikeh: RJ employees are against Samer A.Majali resignation.. according to rum online http://watwet.com/u/93932b

ParseKit - Cocoa Objective-C Framework for parsing, tokenizing and language processing

by Jörg Battermann | about 3 hours ago | Read more

ParseKit - Cocoa Objective-C Framework for parsing, tokenizing and language processing: I’ve been working a lot with string tokenization and bnf grammar syntax so it’s nice to see a framework for that in obj-c, too.

6257 Ich find die Temperatur ja geil... Vor allem auf der Wiese am Rursee :)

by Michael Simons | about 4 hours ago | Read more

Michael
Ich find die Temperatur ja geil... Vor allem auf der Wiese am Rursee :)

In_the_office_profile Watwet from mudoveee [04/07/2009 14:10]

by Waheed Barghouthi | about 4 hours ago | Read more

again bun ultima vrema :D

In_the_office_profile Watwet from mudoveee [04/07/2009 13:55]

by Waheed Barghouthi | about 4 hours ago | Read more

Remembering the king of pop, listening to a couple of his greatest songs right now

Feed Parsing

by Eifion Bedford | about 4 hours ago | Read more

In this episode we use two different techniques to parse an RSS feed with Feedzirra.

742004_icon Mobile Monday Delhi: 7th Edition

by Manik Juneja from India | about 5 hours ago | Read more

Just got this email from PacificLeo announcing MoMo Delhi 7th Edition: Hi Guys I am Very excited to inform you that we have finalized the schedule for next meet up of Mobile Monday,Delhi. This will be our seventh Meet up.Its scheduled for Saturday ,11th of July 2009. Theme for this time is Mobile [...]

Ichaug2 Unlogisch

by Klaus Breyer | about 5 hours ago | Read more

Man kann sich nicht über Denkvorgänge bei Frauen beklagen und im nächsten Satz sich gegen Mathematik in der Schule aussprechen (”braucht man doch eh nie wieder”). Entweder man ist für oder gegen Logik – alles andere ist unlogisch. Weiterführende Lektüre: Die koaxialen scheitelrechten Hyperboloide und der tetraedrale Komplex ihrer Strahlen

Запуск дочерних процессов в руби

by Shaliko | about 5 hours ago | Read more

Около дюжины способов запуска под-процессов в руби

My120_135 RE: проблема при использования attachment_fu для аплоада

by Ruslan Voloshin | about 5 hours ago | Read more

Учти следующий момент. Я сам не разбирался, но напарник как то правил следующую штуку:

Наш любимый Ослик пи загрузке файлов Мимик ставит не как все, а какой-то свой.

Так при использовании papperclip нам пришлось писать такую валидацию на тип мимика:

<code:ruby> validates_attachment_content_type :avatara, :content_type => ['image/jpeg', 'image/gif', 'image/png', 'image/pjpeg', 'image/x-png', 'image/jpg'],
:message=>"Файл данного типа не может быть загружен"

My120_135 RE: Разграничение прав доступа

by Ruslan Voloshin | about 6 hours ago | Read more

Ммм даааа.

Вообще, судя по информации - задача не тривиальная. Ну что ж, тем интересней.
На самом деле я занимаюсь этим вопросом довольно давно. Только сейчас в голове созрела общая, и на мой взгляд, довольно красивая схема решения. Сейчас и занимаюсь тем, что ее реализую. Подумал, что возможно кто то сможет ткнуть меня носом в то, что все давно украдено до нас =)

А пока буду работать над своей реализацией.
Спасибо.

In_the_office_profile Watwet from mudoveee [04/07/2009 12:15]

by Waheed Barghouthi | about 6 hours ago | Read more

Had a great night yestetday, and still not ready for anything since morning :s

B5f91372b2a16a7a8c5b3cd27533f246?s=80 rares started watching rklophaus/nitrogen

by Rob Ares | about 6 hours ago | Read more

rares started watching rklophaus/nitrogen: nitrogen’s description: Nitrogen Web Framework...

B5f91372b2a16a7a8c5b3cd27533f246?s=80 rares started following dojo

by Rob Ares | about 6 hours ago | Read more

rares started following dojo: dojo has 5 public repos and 23 followers.

B5f91372b2a16a7a8c5b3cd27533f246?s=80 rares started watching grempe/amazon-ec2

by Rob Ares | about 6 hours ago | Read more

rares started watching grempe/amazon-ec2: amazon-ec2’s description: A Ruby Gem that gives...

B5f91372b2a16a7a8c5b3cd27533f246?s=80 rares started watching jtrupiano/timecop

by Rob Ares | about 6 hours ago | Read more

rares started watching jtrupiano/timecop: timecop’s description: A gem providing a unified...

In_the_office_profile Watwet from triplem [04/07/2009 12:10]

by Waheed Barghouthi | about 6 hours ago | Read more

Fb RT @t3ajdotcom: 3ala 7azz El 7azineh, Sakkarit El Madineh - على حظ الحزينة سكّرت المدينة http://watwet.com/u/5f2cfd

In_the_office_profile Watwet from jarkas [04/07/2009 12:00]

by Waheed Barghouthi | about 6 hours ago | Read more

RT: @Razaniyyat: قصة الطفلة خولة التي تعرضت للاغتصابhttp://watwet.com/u/a16b48 http://watwet.com/u/c8a39c

6 aizatto: @razlanshah wrt 50 people. yes they would to. has been proven.

by Ezwan Aizat bin Abdullah Faiz | about 6 hours ago | Read more

aizatto: @razlanshah wrt 50 people. yes they would to. has been proven.

ManyBooks.net – Public Domain eBooks

by Sachin Khosla | about 6 hours ago | Read more

This post is a quick note about one of my favorite sites – ManyBooks.Net. ManyBooks is an archive of a number of Project Guttenberg, Public Domain and Creative Commons etexts. What it thus becomes is a library of classic literature and text (starting from Vigil and Herodotus, to the contemporary) on and around culture, literature [...] No related posts.

My120_135 RE: RE: RE: проблема при использования attachment_fu для аплоада

by Ruslan Voloshin | about 6 hours ago | Read more

monkey patch:
<code:ruby>
require 'tempfile'
class Tempfile
def size
if @tmpfile
@tmpfile.fsync
@tmpfile.flush
@tmpfile.stat.size
else
0
end
end
end


И все заработает

My120_135 RE: Разграничение прав доступа

by Ruslan Voloshin | about 6 hours ago | Read more

lockdown. это гем.

Правда, он слегка сыроват. Мне пришлось его в нескольких местах сразу monkey-патчить.

Ну, а особенности вашей системы придется писать самому (3,4,5 пункты).

Allstate agency owner wins national award

by AlexLiteev | about 7 hours ago | Read more

Allstate Insurance has recognized Dave Mlynarik, owner of the company’s Westfield office, with the Chairman’s Conference award for high standards in customer satisfaction, customer retention and profitable business growth. The Dave Mlynarik Agency is among 6 percent of insurance agencies and personal financial representatives for Allstate nationwide to reach this level of achievement, based on sales [...]

15e1ad779efb8622fce3c7fd7232636a ʬ: Modernizr [del.icio.us]

by Ian Fieldhouse | about 7 hours ago | Read more

Modernizr is a small and simple JavaScript library that helps you take advantage of emerging web technologies (CSS3, HTML 5) while still maintaining a fine level of control over older browsers that may not yet support these new technologies.

TemplateWire

by Brian McManus | about 7 hours ago | Read more

TemplateWire

TemplateWire offers premium XHTML / CSS website templates, flash templates, logo templates at affordable prices. Created by professional designers, built with simplicity, versatility and ease of use in mind, our premium design products are available for immediate download.

My120_135 RE: RE: Папку в архив.. как?!

by Ruslan Voloshin | about 7 hours ago | Read more

Ну ничего.. ) И на этом спасибо..

Удачи)

My120_135 RE: Папку в архив.. как?!

by Ruslan Voloshin | about 7 hours ago | Read more

=) если б я хоть раз это использовал сам, я б обязательно ответил =)

My120_135 RE: RE: Папку в архив.. как?!

by Ruslan Voloshin | about 7 hours ago | Read more

Спасибо, Илья.. ) Как раз то что нужно.. ^_^



Только вопрос: когда скрипт заканчивает работу - в папке рядом с архивом находятся еще какие-то файлы.. Очень странные.. Частично состоящие из названий файлов что я в архив упрятал + дата + что-то еще.. А внутри файлов - информация из заархивированных файлов..



Это можно как-то убрать?!

Dm Vyplatí se refaktorizovat i starý kód?

by David Majda | about 7 hours ago | Read more

Každý větší program má v sobě alespoň jeden kus kódu, na který se dlouhou dobu nesahalo, protože to prostě nebylo potřeba – funguje a dělá to, co má. Kvalita takového kódu je ale obvykle nižší než kvalita zbytku programu, protože se mu nedostalo dalšího vývoje a refaktorizací.

Joakim Karlsson si všiml zajímavé věci: pokud do takového kódu z nějakého důvodu po dlouhé době zasáhnete, je vysoká pravděpodobnost, že do něj brzy budete muset zasahovat znovu. Změny mají tendenci se kupit, při testování narazíte na chyby v původním kódu apod. Je to poněkud neintuitivní, ale i dle mé zkušenosti to tak opravdu je.

Co toto pozorování znamená pro praxi? Při zásazích do starého kódu je obvyklé provádět změny způsobem, který se co možná nejméně dotkne stávajícího kódu, a to i za cenu nižší kvality výsledku. Logika velí, že nemá smysl se snažit cokoliv měnit a vylepšovat, když se sem stejně nikdo zase dlouho dívat nebude. Joakimovo pozorování právě tuto logiku narušuje a indikuje, že i starý kód se může vyplatit začišťovat a refaktorizovat – zkrátka aktivně zlepšovat jeho kvalitu, stejně jako u kódu živého – protože ve skutečnosti není tak mrtvý, jak se zdá.

Joakim se snaží své pozorování dokládat na analýze Subversion repository Pythonu a GCC. Jeho metodika je ale velmi sporná – měří intervaly mezi změnami ve všech souborech, nijak neodlišuje starý kód. Dochází tím pádem neodvratně k histogramu s exponenciálním rozdělením, což by předpověděl každý absolvent kurzu pravděpodobnosti a statistiky.

Celý článek je tak třeba brát spíš jako anecdotal evidence a námět na zamyšlení a diskuzi. Vzhledem k tomu, že údržba starého kódu je reálný problém, by se ale myslím vyplatilo problém prozkoumat trochu hlouběji.

2589751456_cba18fdcde Links for 2009-07-03 [del.icio.us]

by John Wulff | about 8 hours ago | Read more

2158401659_9e87d23dcb_m Links for 2009-07-03 [del.icio.us]

by Reginald Braithwaite | about 8 hours ago | Read more

196b781eef85b7ce609fd12234cc1f39 Links for 2009-07-03 [del.icio.us]

by Jeff Schoolcraft | about 8 hours ago | Read more

Links for 2009-07-03 [del.icio.us]

by Stefano | about 8 hours ago | Read more

  • Schedules Direct
    The primary benefit we provide to our members is access to raw U.S./Canadian TV listing data for the Free and Open Source Applications they use. Those applications then use the data to provide things like PVR functionality, search tools, and private channel grids.

Dsc00216_mini_ Links for 2009-07-03 [del.icio.us]

by Cairo Noleto | about 8 hours ago | Read more

Iphoto_bigger Links for 2009-07-03 [del.icio.us]

by Dylan Zheng | about 8 hours ago | Read more



Tell us what you think of the new BlogSphere feature. We are continually looking to improve and update the functionality based on your feedback.

Job Board

Job Boards
Find your next Ruby on Rails project or job.
Exclusive content, regularly updated - onsite and tele-working positions listed.

View the opportunities

Latest from the Weblog

Recent Recommendation

Pat Nakajima:

Pat is a hacker and his code is a pleasure to use.

- Sbubble B.C, United States