Define application constants in Rails

Some days ago I was trying to find an elegant way to add application constants in Rails. Searching the net I found this gem: https://github.com/binarylogic/settingslogic
I will try to make a small tutorial below. For more information see readme file from git repository.

1) Install gem file:


sudo gem install settingslogic

2) create a class in models named Settings or any other name you want. save it as settings.rb:


class Settings < Settingslogic
source "#{Rails.root}/config/application.yml"
namespace Rails.env
end

3) create a yml file with settings in app/config/application.yml. An example of content:


# app/config/application.yml
defaults: &defaults
cool:
saweet: nested settings
neat_setting: 24
awesome_setting: <%= "Did you know 5 + 5 = #{5 + 5}?" %>

development:
<<: *defaults
neat_setting: 800

test:
<<: *defaults

production:
<<: *defaults

4) Now you can access this settings like this:


>> Rails.env
=> "development"

>> Settings.cool
=> “#”

>> Settings.cool.saweet
=> “nested settings”

>> Settings.neat_setting
=> 800

>> Settings.awesome_setting
=> “Did you know 5 + 5 = 10?”

With this gem you can configure different configuration for specific environments.
Hope this helps you create more elegant code.

Advertisements

Jquery autocomplete plugin in Rails 3

This post tries to show how to user rails3-jquery-autocomplete gem in Rails 3.

  1. create a new application:

    rails new jquery-autocomplete

  2. chage directory to application:

    cd jquery-autocomplete

  3. change application javascript files to jquery. For this follow this tutorial :
    https://silviurosu.wordpress.com/2010/12/05/change-rails-js-to-jquery-from-prototype-and-scriptaculous/
  4. edit gem file and add rails3-jquery-autocomplete dependency:

    gem ‘rails3-jquery-autocomplete’

  5. update dependencies:

    bundle install

  6. generate autocomplete file:

    rails g autocomplete

    Should result:

    create public/javascripts/autocomplete-rails.js

  7. go to http://jqueryui.com/download and download a build with autocomplete selected
  8. unpack the zip file and copy jquery-ui -x.x.x.custom.min.js in application javascript directory and all of the content of css/ui-lightness directory to public/stylesheets directory
  9. edit application.html.erb file and change head to:

    <head>
    <title>JqueryAutocomplete</title>
    <%= stylesheet_link_tag :all %>
    <%= javascript_include_tag :defaults %>
    <%= javascript_include_tag “autocomplete-rails”, “jquery-ui-x.x.x.custom.min” %>
    <%= csrf_meta_tag %>
    </head>

  10. generate a model to load data from:

    rails generate model Category name:string
    Console result:
    invoke active_record
    create db/migrate/20101205100113_create_categories.rb
    create app/models/category.rb
    invoke test_unit
    create test/unit/category_test.rb
    create test/fixtures/categories.yml

  11. crete database for this application:

    rake db:create

  12. run the migration to update the database with categories table:

    rake db:migrate
    Console result:
    == CreateCategories: migrating ===============================================
    — create_table(:categories)
    -> 0.0778s
    == CreateCategories: migrated (0.0779s) ======================================

  13. run the console to add some data in this table:

    rails console

  14. create 10 records in categories table:

    Category.create(:name => “Art”)
    Category.create(:name => “News”)
    Category.create(:name => “Toys”)
    Category.create(:name => “Clothes”)
    Category.create(:name => “Cars”)
    Category.create(:name => “Art”)
    Category.create(:name => “Television”)
    Category.create(:name => “Nature”)
    Category.create(:name => “Recycle”)
    Category.create(:name => “Internet”)
    Category.create(:name => “House”)
    Category.create(:name => “Indoor”)

    Console result should be after each command like this:
    => #<Category id: 1, name: “Art”, created_at: “2010-12-05 10:09:22”, updated_at: “2010-12-05 10:09:22”>

  15. now let’s create a controller to call for the autocomplete data:

    rails generate controller categories
    Console result:
    create app/controllers/categories_controller.rb
    invoke erb
    create app/views/categories
    invoke test_unit
    create test/functional/categories_controller_test.rb
    invoke helper
    create app/helpers/categories_helper.rb
    invoke test_unit
    create test/unit/helpers/categories_helper_test.rb

  16. edit categories_controller and add index method to list all categories:

    def index
    @categories = Category.all
    end

  17. create index view file in views/categories.index.html.erb with the following content:
  18. <h1>Categories</h1>
    <ul>
    <% @categories.each do |category| %>
    <li><%=category.name%></li>
    <%end %>
    </ul>

    <%= link_to “Add new category”, new_category_path %>

  19. then we have to add routes for Category actions. Add in the routes.rb:

    resources :categories

  20. You can test the view. Point to http://localhost:3000/categories and you should see the list of categories. Also there is a link for a new category.

  21. add the new method in the controller to receive the request from the link:

    def new
    @category = Category.new
    end

  22. create new.html.erb view file to display the form for creating a new category:

    <h1>Create new category</h1>
    <%= form_for @category do |f| %>
    <%= f.label :name, “Category:” %>
    <%= f.text_field :name %>
    <%= f.submit “Submit”, :disable_with => ‘Submiting…’ %>
    <% end %>

  23. create the controller method to create a new category:


    def create
    @category  = Category.new(params[:category])
    if @category.save
    flash[:notice] = "Category was successfully created."
    redirect_to categories_url
    else
    render :action => "new"
    end
    end

  24. Now let’s make autocomplete fuctionality on new controller form.

  25. add to categories_controller:

    autocomplete :category, :name

    and

    resources :categories do
    get :autocomplete_category_name, :on => :collection
    end

  26. change new.html.erb from point 20 to:

    <h1>Create new category</h1>
    <%= form_for @category do |f| %>
    <%= f.label :name, “Category:” %>
    <%= f.autocomplete_field :name, autocomplete_category_name_categories_path %>
    <%= f.submit “Submit”, :disable_with => ‘Submiting…’ %>
    <% end %>

  27. Now run the server and test the autocomplete functionality. It should be working and find the category selected if exists.
    More information can be found on rails3-jquery-autocomplete git hub

Change rails js to Jquery from prototype and scriptaculous

For those who are more familiar with jquery than prototype and scriptaculous you can switch to jquery. This are the steps required to create a new application with jquery support:
1) create a new application with:

rails new application_name

2) change directory to new application:

cd application_name

3) install jquery-rails gem file

gem install jquery-rails

4) edit Gemfile and add:

gem 'jquery-rails'

5) update application dependencies:

bundle install

6) generate jquery files:

rails generate jquery:install

This will remove controls.js, dragdrop.js, effects.js, prototype.js and download in the application jquery.js, jquery.min.js. Then will promt to override rails.js

Thats all. Now all the rails javascript is jquery.

Multiple file upload with JQuery

I had to implement multiple file upload in a form to add dynamically more files. Searching the web I discovered a plugin for jQuery that does that. It’s called “jQuery Multiple File Upload Plugin”. Site url is: http://www.fyneworks.com/jquery/multiple-file-upload/

Basic usage:

Use js file from: http://jquery-multifile-plugin.googlecode.com/svn/trunk/multiple-file-upload.zip

Import script in page:

<script src="jquery.MultiFile.js" type="text/javascript" language="javascript">
</script>

And use it in form like this:

<input type="file" class="multi"/>

Also you can limit the number of inputs or restrict file types:

<input type="file" maxlength="2" accept="gif|jpg"/>

More help you can fing on plugin site.

See you at the top(Pe culmile succesului) – Zig Ziglar

Few words about the author:

It is an American motivational speaker and writer and wealthy business men who succeeded in life starting from the bottom. He was a poor sales agent struggling to feed his family until he realized that every people has the potential to be successful if he trust in him. A video to see how much enthusiast he puts in what he does:

I read some time ago this phenomenal book and now I’m reading again because I find it very valuable for personal development. When you read this book you feel real life experience and realize that you can accomplish anything you want.  It’s one of those books that breads real life experience through every page.

The essence of this book is the pyramid stairs a man has to climb to reach success in life:

  1. self image
  2. relationships with others
  3. goals
  4. attitude
  5. hard work
  6. desire

This steps followed one by one tells him take us to: health, wealth, happiness, friends, progress, calm, safety, free time, freedom.

1)The best thing to prepare us for life is self image. If we have a good self image the rest will follow but a bad self image will bury us alive and we will waste our life with fear of taking responsibility in life.

2) We can’t succeed in life alone, we need help from the others and we need a team to win. If we help others reach theirs dreams they will help us reach ours. The people will give you all they have best if you will give them all you have best.

3) The only way to reach the top is to have a goal. You can’t climb the stairs if you don’t want to go somewhere. (No one will ever say: “I was walking by when I reached Everest mountain top”)

4) We can change our life changing our attitude. A positive attitude will bring positive results because attitudes are contagious. React positive in negative situations. We can’t choose life situations but we can choose our attitude.

5) The most interesting, practical life philosophy will not succeed if you will not take the effort required. Why give up now when you can give up tomorrow?

6) The desire is the ingredient that transforms the mediocrity in an astonishing success. The desire is the ingredient that differentiate a champion from a regular player.

In the next posts I will detail every steps…