Showing posts with label guide. Show all posts
Showing posts with label guide. Show all posts

Thursday, March 3, 2011

How to submit an ajax form in javascript with Rails3 and Prototype

So there is a Rails 3 problem, when you want to submit a form in javascript (without a submit button), it is working on normal way, not ajax. But we can do creating a hidden submit button and then initializing a click event on it what is exactly doing ajax submission. The submit(); is not working anymore because it doesn't call the rails.js functions. It just works when you simple want to create a not ajax post without any confirmation. Let's see an ajax example in view's index.html.erb file:

<%= form_tag "some_url",
 :remote  => true,
 :method  => :post,
 :name  => "some_procedure",
 :id   => "some_procedure" %>
<%= submit_tag 'procedure_submit_button', :id =>"procedure_submit_button" , :style => "display: none" %>

You can add here your html code for form and create some element what is doing the submission inside a table, for a td:

<td onclick="javascript: procedure_init();" style="cursor: pointer;">

put here an image for example

</td>

</form>

<%= javascript_tag <<-RUBY
function procedure_init()
{
 var submit_button="procedure_submit_button";
 var form_name="some_procedure";
 // here you can build the form, or modify form parameters
 $(submit_button).click();
}
RUBY
%>

If you have problems with sessions or current_user quits within ajax rendering, put this code to public/javascripts/application.js. /thanks to this answer/

document.observe("dom:loaded", function() {
 Ajax.Responders.register({
  onCreate: function(request) {
   var csrf_meta_tag = $$('meta[name=csrf-token]')[0];
   if (csrf_meta_tag) {
    var header = 'X-CSRF-Token',
      token = csrf_meta_tag.readAttribute('content');

    if (!request.options.requestHeaders) {
     request.options.requestHeaders = {};
    }
    request.options.requestHeaders[header] = token;
   }
  }
 });
});

That's all. Questions?

Monday, November 22, 2010

Each loop for a class or model instance variables

Sometimes we need to check all of instance variables in a class or model one by one. In this exaple we will check if a varaible is an Array or not:

your_model.instance_variables.each do |i|
 if your_model.instance_variable_get(i).instance_of?(Array) then
  #your code to do anything with your_model.instance_variable_get(i) what is a value
 end
end



If you have an active record model, you can do:

@account = Account.first

Account.column_names.each do |i|
  @account.instance_eval(i)
 # row returns @account.name for example inside the loop, next @account.address and so on
end





That's all!

How to get requested controller name, action name and id in Rails3 view

To get requested controller name, action name and id in view we will call a simple helper function. For example we have the '/users/show/23' request, by routing rule: 'match ':controller(/:action(/:id(.:format)))''


#to get controller name:
<%= controller.controller_name %>
#=> 'users'

#to get action name, it is the method:
<%= controller.action_name %>
#=> 'show'


#to get id information:
<%= ActionController::Routing::Routes.recognize_path(request.url)[:id] %>
#=> '23'


That's all!

Monday, November 8, 2010

I18n yml files in Rails3

Your locale files are located in config/locales directory by default. Let's make two locale files: en.yml and for example: hu.yml. In that files we can describe our string translations what we will use in our page view with helpers. Take care of yml rules, you can use spaces only instead of tabs, and spaces determine level of string. You can use double quotes to define a string, but if you want to use quotes inside the string, use html entity: " for it. You can use html in strings fo course, but don't forget raw helper in view before. Finally, you can give variables to yml simply, between %{var} (in rails2: {{var}} ) signs and full string needs to be between double quotes. I used to create yml blocks by controllers.


Labels are very simple also. Just take under helpers: and controller_name: (helpers: and contact: in the example below). Submit definitions are the same like labels.


en:
  contact:
    prices:
      show_price: "%{price_dollar}$"
      quote: "Coordinator: & quot;Crucifixion?& quot? & lt;br /& gt; Mr. Cheeky: & quot;Er, no, freedom actually.& quot;"

  attributes:
    created_at: "Created at"
    updated_at: "Updated at"

  helpers:
    submit:
      contact:
        create: "Order"
        update: "Modify"
    label:
      contact:
        name: "Your name"
        company_name: "Company name"
        phone: "Phone number"
        email: "E-mail"
        comment: "Comment"

  date:
    formats:
      default: "%Y-%m-%d"
      short: "%b %d"
      long: "%B %d, %Y"
    day_names: [Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday]
    abbr_day_names: [Sun, Mon, Tue, Wed, Thu, Fri, Sat]
    month_names: [~, January, February, March, April, May, June, July, August, September, October, November, December]
    abbr_month_names: [~, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec]
    order: [ :year, :month, :day ]
 
  time:
    formats:
      default: "%a, %d %b %Y %H:%M:%S %z"
      short: "%d %b %H:%M"
      long: "%B %d, %Y %H:%M"
    am: "am"
    pm: "pm"


And the reference in our view file (apps/views/contact/index.html.erb):


<%= form_for @contact, :as   => :contact,
   :url  => {:action => 'new'},
   :html => {} do |f| %>

<%=f.label :name %>

<%= f.submit %>

<%=t :show_price, :scope => [:contact, :prices], :price_dollar => 50 %>

<%=raw t(:quote, :scope => [:contact, :prices], :locale=>'en') %>
<%=l Date.today, :format => :long %>

You can define exact locale in view like :locale=>'hu'. Localize dates with l helper function. You can use I18n.locale in controller for getting current locale. You can get all locales in an array with: I18n.available_locales . Don't forget to check application.rb in config directory, where you can setting up default locale:


config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
     config.i18n.default_locale = :hu

Then make a method in app/controllers/application_controller.rb for users to change their language and create a before_filter:


class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :set_locale

  def set_locale
  locale = params[:locale] || session[:locale] || I18n.default_locale.to_s
  locale = I18n.available_locales.include?(locale.to_sym) ? locale : 18n.default_locale.to_s
  session[:locale] = I18n.locale = locale
  end
end

Then create your link to set locale in your layout: link_to('English', url_for(:locale => 'en')). That's all! Questions?

Wednesday, November 3, 2010

Rails3 ajax tricks with javascript erb templates

This guide is about rails3 ajax and javascript tricks. (Unobtrusive javascript, if it sounds better.) first, you must decide what do you want to do and how. Sometimes there are better solutions than we should think first. To call an ajax method, you must take the code in view header (or layout): <%= javascript_include_tag :defaults %>

Using js.erb templates.

If you decided to use some ajax calls, using server-side programming, recommend to create a new ajax controller (but it's not necessary). In command line:

rails g controller ajax

Then, if we make an ajax call, we will define procession in app/controllers/ajax_controller.rb. Next, we define the javascript output in ajax_controller.rb with respond_to, and define our methods (now: empty_cart):

class AjaxController < ApplicationController
respond_to :js

  def empty_cart
    Cart.where(:session_id => request.session_options[:id]).destroy_all
  end

end

Then we can create empty_cart.js.erb in app/views/ajax/ directory. In this file we define javascript what sends to page. This is javascrip template, but we can use ruby expressions in it. Of course, we can use prototype methods and script.aculo.us effects. The partial cart.html has been defined in layouts and if cart is empty, it will show one row: "the cart is empty". The element will be replaced by partial:


$("cart_div").update("<%= escape_javascript(render("layouts/partials/cart.html.erb")) %>");
new Effect.Highlight("cart_div", {duration: 1.5, startcolor: "#909090"});

After then, we can create this ajax link in our view, now: layouts/partials/cart.html.erb. We make it with a button defined in css.

<% if Cart.where(:session_id => request.session_options[:id]).empty? %>

Cart is empty.

<% else %>

..put here your cart html code..

<%=raw form_tag url_for(:action => "empty_cart",
  :controller => :ajax ),
{ :method => :post,
  :remote => true,
  'data-confirm'  => "Are you sure?" } %>
<%=raw submit_tag "Empty Cart",
  :id  => "empty_cart_submit",
  :class  => "empty_cart_button"
   %>
</form>

<% end %>

Don't forget to set link html options :remote => true, to call an ajax method.

The right syntax of the link_to function with i18n is:


<%= link_to [t :empty_cart, :scope  => [:application]],
  url_for(:controller => 'ajax',
          :action  => "empty_cart"),
  {:method => :post,
   :remote  => true,
   :confirm => "Are you sure?"}
%>



Using effects

You can use any effects in javascript erb template like in pure javascript. For example a toggle effect:


new Effect.toggle("some_div_<%= id %>", "slide", {duration: 0.2});

Don't forget to put ruby expressions between <%= %> tags like in html view.


Forgetting observe_form and observe_field

In rails 2 there were these functions observe_form and observe_field, now, in rails3 are missing. You can use Prototype Legacy Helper plugin, or, I recommend to create your own javascript code, what is faster than calling an ajax method. Put your javascript code into your form view (app/views/controller_name/form.html.erb):


<%=raw javascript_tag "
document.observe("dom:loaded", function()
{
new Form.Observer("<%= @jsvalidator.form.id %>", 0.3, function(form, value)
 {
// now we got form values in one single url-formed linein value javascript variable
// so we create an array of key and value pairs in textArray
  var textArray=unescape(value).split("&");
  var i=0;
  for(i=0; i<(textArray.length); i++)
  {
// then, you can see all elements within a for loop  
// now textArray[i] is one line like: "form_element_name=form_element_value"
 
   value_line_with_equal_sign=textArray[i];
   value_name="";
   value_value="";
   value_name=value_line_with_equal_sign.split("=",2)[0];
   value_value=value_line_with_equal_sign.split("=",2)[1];
// now you can check all of form values in this loop, value_name is the form element name
// value_value is form element's value
// probably you must give form elements to Form class
 
}
 
}
}" %>

@jsvalidator object has been created in form's controller with form datas. See more information: How to generate inline javascript

If you have problems with Internet Explorer, IE see and download newer versions of rails.js and prototype.js. Details here.


If you have problems with sessions or current_user quits within ajax rendering, put this code to public/javascripts/application.js. /thanks to this answer/

document.observe("dom:loaded", function() {
 Ajax.Responders.register({
  onCreate: function(request) {
   var csrf_meta_tag = $$('meta[name=csrf-token]')[0];
   if (csrf_meta_tag) {
    var header = 'X-CSRF-Token',
      token = csrf_meta_tag.readAttribute('content');

    if (!request.options.requestHeaders) {
     request.options.requestHeaders = {};
    }
    request.options.requestHeaders[header] = token;
   }
  }
 });
});


That's all!

Tuesday, October 26, 2010

How to load i18N locale files in rails3 with our new gem

That is very simple. We'll create a gem with our own locale files, first, we create the locale files in our gem's lib/locales directory (en.yml and hu.yml for example). There would be our gem's .rb file in lib directory (example.rb). Don't forget to specify these files in gemspec. Now we can create a new method: translate_string in our 'lib/example.rb'.


class Example
require 'rubygems'
require 'active_support'
require 'i18n'


path=File.dirname(__FILE__)
I18n.load_path += Dir[ File.join(path, 'locales', '*.{rb,yml}') ]

def initialize
end

def translate_string(var)
  return I18n.t(var, :scope=>[:example, :vars])
end

end

Then, we can create our locale files 'lib/locales/en.yml' like this:


en:
  example:
    vars:
      title: example

And our lib/locales/hu.yml:


hu:
  example:
    vars:
      title: példa

Take care of spaces instead of tabs. After we build our gem and insert to Gemfile (what is in our Rails3 application) we can call our new class in our controller. Don't forget to restart your application before.



e=Example.new
e.translate_string("title")


This gives "example". That's all!

Monday, October 25, 2010

Create new class in Rails3 with hash parameters

This guide is about how to create new class with hash parameters, without ActiveRecord. If you don't want to use database to define a new object, this guide is for you. First, we create a new contact.rb file in "app/models" directory


class Contact
 include ActiveModel::Serialization
 attr_accessor :name, :company_name, :email, :phone, :comment

 def initialize(attributes = {})
  @name=attributes[:name]
  @company_name=attributes[:company_name]
  @email=attributes[:email]
  @phone=attributes[:phone]
  @comment=attributes[:comment]
 end
 
# persisted is important not to get "undefined method `to_key' for" error
 def persisted?
  false
 end 
 
end

And then you can use this model to create a new form, like ActiveRecord in controllers:

@contact=Contact.new

or

@contact=Contact.new(params[:contact])

Now we can use this object to send email to sales or save it to another object's text column with json. For example if there is a json_contact text column in User active_record object, users.rb:


Class User < ActiveRecord::Base
before_save :before_save_function

def before_save_function
  unless self.json_contact.is_a?(String) then
    # we need this condition because if we updating, must know if it is a String (json modelled class) or a Contact model class
    self.json_contact=self.json_contact.to_json
  end
  true
 end

 def contact
  unless self.json_contact.nil? then
   contact_hash = ActiveSupport::JSON.decode(self.json_contact).symbolize_keys.clone
   return Contact.new(contact_hash)
  else
   return nil
  end
 end

end

Then you can give a Contact object to User.json_contact like:

@user=... # your turn (find, or create) @contact=Contact.new(params[:contact]) @user.json_contact=@contact @user.save

Don't forget to restart your application after modifying anything in your models. Now you can get original User.contact as an object, and you can use it like Contact model:

contact_name=@user.contact.name

That's all