Open Source Linux Solutions » Tutorial http://www.xmltree.com Open Source Linux Solutions: Linux Programs, Reviews Programs, Ruby on Rails, Tutorials for Web 2.0 Tue, 12 Feb 2013 17:50:22 +0000 en-US hourly 1 http://wordpress.org/?v=3.4.1 Javascript and physic engines http://www.xmltree.com/?p=136 http://www.xmltree.com/?p=136#comments Mon, 11 Feb 2013 17:40:42 +0000 admin http://www.xmltree.com/?p=136 A few days ago while watching the amazing script.aculo.us combination effect demo page I thought:

A physic Engine written in Javascript could be cool?

With such a tool you could create amazing effects by setting extra physics properties to divs (like forces, frictions, etc…) or other HTML objects. This physic engine could help you create effects like a photo slideshow where the pictures falls from the top and bounch on the bottom of the page.

Other abilities could lead into adding physic effects to your GUI, as example you could have a list of elements (eg divs) one over each other with the ability to delete on of them; when this happen the elements over the deleted one could bounce realistically before stop.

The pourpose of this post is to share this thoughts with you in order to understand if could be a good idea starting the development of such a tool or if there are better alternatives. (or if all these effects are simply unnecessary).

While surfing in the past day searching for already made examples i found only this PhisicBallMenu example dated back (no Prototype.js) and nothing more.

]]>
http://www.xmltree.com/?feed=rss2&p=136 0
BrainBuster Globalized! http://www.xmltree.com/?p=130 http://www.xmltree.com/?p=130#comments Sun, 10 Feb 2013 17:33:36 +0000 admin http://www.xmltree.com/?p=130 During the last week I created a small patch that allows Brain Buster Logic Capthca plugin to cooperate with Globalize by asking only questions that match the specified language.

To archive this I’ve changed ‘brain_buster.rb’ as follow:

def self.find_random_or_previous(id = nil)

@loc = (Locale.language_code.to_s.blank? ? "en" : Locale.language_code.to_s)

if id.nil?

self.find(random_id(first_id, count(:conditions=>["lang = ?",@loc])),:conditions=>["lang = ?",@loc])

else

find(id,:conditions=>["lang = ?",@loc])

end

end

private

# return first valid id

def self.first_id

if find(:all,:conditions=>["lang = ?",@loc], :o rder => "id").length == 0

@loc = "en"

end

@first_id = find(:all,:conditions=>["lang = ?",@loc], :o rder => "id").first.id

end

and then I created a migration which add a ‘lang’ column to the brain buster table:

class BusterAndLanguage < ActiveRecord::Migration

def self.up

add_column :brain_busters, :lang, :string, :default=>"en"

end

def self.down

remove_column :brain_busters, :lang

end

end

That’s it; now we need just to fill the table with questions and answers for the languages we want to add to our application.

]]>
http://www.xmltree.com/?feed=rss2&p=130 0
HOWTO Put a controller under a SSL subdomain http://www.xmltree.com/?p=104 http://www.xmltree.com/?p=104#comments Wed, 06 Feb 2013 16:50:51 +0000 admin http://www.xmltree.com/?p=104 Let’s imagine that you need to create a secure login area, for example if you own http://www.domain.com you may want to put the user login page on https://secure.domain.com. How can you do it?

The best solution in my opinion is to put all the login procedures in a dedicated login controller (eg the ‘sessions’ controller if you are using the RESTful authentication plugin) and then modify a bit the url_for method in order to modify the calls to that controller.

Part 1, A little configuration.

In our environment.rb we’re going to create an array with the name of the controllers we want to put under a different subdomain and under SSL:

SECURE_MODE = [ /\/sessions$/ ].freeze

SECURE_SUBDOMAIN = "secure".freeze

Part 2, Url_for tweaking

Then in our application.rb we have to tweak a bit the url_for function in order to let the defined controllers being handled correctly.

def url_for(options = {}, *parameters_for_method_reference)

tmp_result = super((options.is_a?(Hash) ? options.merge({:only_path => false})

: options), parameters_for_method_reference)

if not (tmp_result =~ Regexp.new(request.host)).nil?

# this tweak is necessary just beacuse I use WebBrick for my development environment (aka I need to specify the port)

if ENV['RAILS_ENV'] == ‘production’

cut_result = tmp_result.to_s.gsub( Regexp.new("#{request.protocol}# {request.host}") ,"" )

elsif ENV['RAILS_ENV'] == ‘development’

cut_result = tmp_result.to_s.gsub( Regexp.new("#{request.protocol}# {request.host_with_port}"), "" )

end

# We’re going to talk about this function later

url_to_go = dispatch_ssl(cut_result)

end

super((url_to_go.nil? ? tmp_result : url_to_go), parameters_for_method_reference)

end

Part 3 Dispatching urls

dispatch_ssl is a function I wrote that receive a partial url (eg /session) and returns the path modified in order to match the new subdomain and protocol rules.

def dispatch_ssl(tmp_result = request.request_uri)

subdomain = SECURE_SUBDOMAIN.blank? ? "" : SECURE_SUBDOMAIN + "."

# need secure is a function that simply check if this path need to be put under SSL

if need_secure?(tmp_result)

if request.protocol == ‘http://’

url_to_go = "https://#{subdomain}" + request.host + tmp_result

end

else

if request.protocol == ‘https://’

host = request.host.gsub(Regexp.new(subdomain),"")

url_to_go = ‘http://’ + host + tmp_result

end

end

return url_to_go

end

Last but not Least: need_secure? and ssl_require

The first function is used by dispatch_ssl to check if the current url match the SECURE_MODE array, the second one (ssl_require) have to be called in a before_filter directive and detects if the user is trying to access a secure area without the correct subdomain and protocol; if this happens the user will be redirected to the correct url.

def need_secure?(uri)

SECURE_MODE.each{ |s|

a = (uri =~ s)

return true unless a.nil?

}

return false;

end

def ssl_required

if not (redir = dispatch_ssl.to_s).blank?

redirect_to(redir) and return false

end

end

]]>
http://www.xmltree.com/?feed=rss2&p=104 0
Create a color picker helper with FormBuilder http://www.xmltree.com/?p=98 http://www.xmltree.com/?p=98#comments Tue, 05 Feb 2013 16:23:35 +0000 admin http://www.xmltree.com/?p=98 Create a FormBuilder

Using a FormBuilder is the easiest way to add new methods to a form_for block; to create a custom FormBuilder simply create a file .rb in your helper directory and put this code inside:

# the custom FormBuilder

class ColorPickerFormBuilder < ActionView::Helpers::FormBuilder

end

What we have just done is created a new FormBuilder by extending the base one, for now we haven’t added any method yet but we can use this builder like the base one; to do this we need just to use the ”:builder” option while calling the form_for method:

<% form_for(:milestone, :url => milestone_path(@milestone.project,@milestone), :html => { :method => :put }, :builder => ColorPickerFormBuilder) do |f| %>
…your form code here…

<% end %>

Adding the color picker method

To add the color picker the only step to perform is write a method named ‘color_picker’ in the formbuilder we’ve previously created:

def color_picker(method, options={})

toret = "<div class=\"colorpicker\">"

options[:avaiable].each_pair do |key,opt|

toret += "<div id=\"coloritem_#{key}\" class=\"coloritem " + (opt == options[:selected] ? "cpselected" : "") + "\" style=\"background: #{opt}\">"

toret += "<a href=\"#\" onClick=\"set_color_picker(‘coloritem_#{key}’,'#{opt}’);return false;\"></a>"

toret += "</div>\n"

end

toret += "<input type=\"hidden\" name=\"#{@object_name.to_s}[#{method.to_s}]\" value=\"#{options[:selected]}\" id=\"hidden_color_picker\"/>"

toret += "<div class=\"clear\"></div>"

toret += "</div>"

return toret

end

Now we can call this new control in the same way we would use for a text_field or a text_area:

… in your environment.rb file…

MIL_TYPES = { 1 => "#ff6600",

2 => "#785f4b",

3 => "#56bb98",

4 => "#786575",

5 => "#000000"

}.freeze

… inside a form_for block …

<%= f.color_picker :color, :avaiable => MIL_TYPES, :selected=> @milestone.color %>

CSS and Javascript

The last step is to do a little styling of this controller and add a bit of javascript:

In your CSS file:

div.coloritem{

float: left;

margin-left: 5px;

width: 20px;

height: 20px;

}

div.cpselected{

border: 2px solid #000000;

}

div.coloritem A{

display: block;

width: 100%;

height: 100%;

}

In your javascript file (usually application.js):

function set_color_picker(element_name,color){

items = document.getElementsByClassName(‘coloritem’);

for(x=0;x<items.length;x++){

Element.removeClassName(items[x],’cpselected’);

}

Element.addClassName(element_name,’cpselected’)

document.getElementById(‘hidden_color_picker’).value = color

}

]]>
http://www.xmltree.com/?feed=rss2&p=98 0
Howto create a new action with a resource http://www.xmltree.com/?p=89 http://www.xmltree.com/?p=89#comments Mon, 04 Feb 2013 16:06:39 +0000 admin http://www.xmltree.com/?p=89 By the time I’m writing, RESTful applications are in very high position in the top chart of the best software architecture for web applications. So why not to talk about this new way of programming ? :-) In this (small) how to i just want to show you how to add a personalized action inside a scaffolded resource; ok, let’s start!

First of all we need to create a rails application, and then to configure database.yml file to match our database parameters. Once this is done just move inside your application folder and write:

ruby script/generate scaffold_resource message title:string body:string

This simple command will generate a lot of stuff, in detail:

  • A controller named messages_controller
  • A model named message
  • A migration named xxx_create_messages
  • A view folder named message that contains all the scaffold view
  • Fixture and unit tests for the model and the controller

This command also add a line in your ‘config/routes.rb’ file:

map.resources :messages

Ok, now you have a RESTful scaffold, but what if you want to add a new action (for example a ‘read’ flag) ? It’s quite easy: first of all we need a new migration:

ruby script/generate migration read_flag

Now open xxx_read_flag.rb and add:

class ReadFlag< ActiveRecord::Migration

def self.up

add_column :messages, :read, :boolean, :default => false

end

def self.down

remove_column :messages, :read

end

end

Then execute rake db:migrate to synchronize your database with the current migration.

Ok, these steps are not so different from the old-school way of coding, but the following will be. We’re going to map our new action inside our resource, Rails let us choose which HTTP method we want to bind with our action; one of the REST guidelines tell us that we have to map INSERT actions with a HTTP POST method, and UPDATE with PUT, so we have to add to routes.rb:

map.resources :messages, :member => { :read => :post }

Ok, we have just set up a new url: ’/message/n;read’ where n is for the message id, now the most is done, the next steps involve the creation of a read action inside the message controller and the creation of a link (with method post) inside our list view that point to that action.

# Part 1: define the action (inside messages_controller.rb)

def read

respond_to do |format|

if Message.find(params[:id]).update_attribute(:read, true)

format.html { redirect_to message_path }

format.xml { head :o k }

else

format.html { redirect_to message_path }

format.xml { head 500 }

end

end

end

# Part 2: link the action inside our list view (inside/app/views/messages/index.rhtml)

<td><%= link_to ‘Show’, message_path(message) %></td>

<td><%= link_to ‘Edit’, edit_message_path(message) %></td>

<td><%= link_to ‘Destroy’, message_path(message), :confirm => ‘Are you sure?’, :method => :delete %></td>

<td><%= link_to ‘Set the read flag’, read_message_path(message), :method => :post %></td>

And with these last steps we have added our read action keeping the REST model valid. If you need more informations about REST architecture i suggest you to read this pdf: RESTful Rails Development freely avaiable at b-simple-de.

]]>
http://www.xmltree.com/?feed=rss2&p=89 0
Tutorial: Opensearch with Rails 1.2 render :json http://www.xmltree.com/?p=62 http://www.xmltree.com/?p=62#comments Thu, 31 Jan 2013 14:37:52 +0000 admin http://www.xmltree.com/?p=62 As you might have noticed this website has a personalized search plugin that you can install by click on the browser search field; in fact this plugin is just an XML file ( you can find it here ) that tell your browser how to perform searches on this website.

Looking at the OpenSearch description page I found that is possible to specify an url that return suggests during the search; the google search plugin has this possibility: while you’re typing on the search box it displays suggests that you can click.

In this tutorial we are going to use this “suggests feature” of opensearch to show cities that partially match what the user wrote in the searchbox.

Step 1: application

Ok, just create a new Rails application, a controller (search) with three actions, (index, suggest and you_choose) and a model (cities) that will hold all the American cities.

rails jsondemo

cd jsondemo

ruby script/generate controller search index suggest you_choose

ruby script/generate model city

I found this useful SQL file that holds all the American city names that we could use to populate our ‘cities’ table (Ok, no YAML but this is just a proof-of-concept application).

Step 2: search.xml

Now we have to create a search.xml file and put it into our public directory inside jsondemo app. The .xml file will look like this:

<?xml version="1.0" encoding="UTF-8"?>

<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">

<ShortName>US cities lookup</ShortName>

<Description>Us cities lookup</Description>

<InputEncoding>UTF-8</InputEncoding>

<Image height="16" width="16" type="image/x-icon">URL-TO-AN-ICON-FILE</Image>

<Url type="application/x-suggestions+json" template="http://YOUR-ADDRESS/search/suggest?city={searchTerms}"/>

<Url type="text/html" method="GET" template="http://YOUR-ADDRESS/search/you_choose/{searchTerms}"/>

</OpenSearchDescription>

of course you have to replace URL-TO-AN-ICON-FILE and YOUR-ADDRESS with an url that point to a .ico file and with the url of your application.

This .xml file tell Firefox what is the name (and the description) of your search plugin, what is the icon to put inside the search box, what url has to be called when you press enter and what is the url that point to the suggest page. Please note that ‘{searchTerms}’ is filled each time by Firefox with the phrase inside the searchbox.

Step 3: the search controller

When we created the search controller (step 1) we defined 3 actions: let’s see them in details:

  • index – it is the homepage of our applications.
  • you_choose – it is the page Firefox call when someone press enter in the searchbox, in this page we have to display the name of the city the user choose.
  • suggest – In this action we will search for the cities that partially matches the one typed by the user and we will render our result in JSON format.

Ok, with this idea in mind the controller will look more or less like this:

class SearchController < ApplicationController

def suggest

codes =City.find(:all,:conditions=>["cityname LIKE ?",params[:city]+"%"],:limit=>10,:group=>"cityname",:order=>"cityname")

@res = codes.map{ |c| c.cityname }

render :json=>[params[:city],@res].to_json

end

def index

end

def you_choose

@city = City.find(:first,:conditions=>["cityname LIKE ?",params[:city]+"%"],:limit=>10,:group=>"cityname",:order=>"cityname")

end

end

Note that here we could merge the two searches by adding a method to the model (here is DRY violating).

Step 4: Basic template settings

Ok at this point to see all this things run we have just to tell Firefox that there is a search plugin avaiable in our application. To do this just add this line to your ‘layouts/search.rhtml’

<link rel="search" type="application/opensearchdescription+xml" title="Search a City" href="http://YOUR-ADDRESS/search.xml" />

Before starting the WebBrick server just remember to create two views for the ‘index’ and the ‘you_choose’ action.

]]>
http://www.xmltree.com/?feed=rss2&p=62 0
Tutorial: migrate plugin schemas using Ruby on Rails 1.2 http://www.xmltree.com/?p=51 http://www.xmltree.com/?p=51#comments Tue, 29 Jan 2013 14:16:17 +0000 admin http://www.xmltree.com/?p=51 Writing plugins is an essential task for a ninja ruby on rails programmer, plugins are flexible, portable and helps maintaining the application code really clean.

But, what happens when you need to create a startup database schema for your plugin? Obviously you cannot attach a .sql file just next to README… this is not the Ruby on Rails way!

Luckily our problems are ended! Using the Rails 1.2 RC1 version and 3 plugins you can add a marvelous db:migrate:plugins task to your app!

First of all freeze rails at the 1.2 RC1 version:

rake rails:freeze:edge TAG=rel_1-2-0_RC1

Then install the three required plugins:

  • Plugin dependencies
  • Loaded plugins
  • Plugin migrations

Now just put your plugin migrations inside the plugin db folder and you can finally use tasks like.

rake db:migrate:plugins

rake db:migrate:plugins PLUGIN=acts_as_random

rake db:migrate:plugins PLUGIN=acts_as_random VERSION=3

]]>
http://www.xmltree.com/?feed=rss2&p=51 0