Archive

Archive for the ‘RubyonRails’ Category

Learn to build a Rails app using Heroku and Git

November 8th, 2009 admin No comments

Hi All:

I have recently discover Heroku service for building applications. It is extremely useful and extremely easy to use. It is also based in Git a SCM system which is also revolutionazing the version control systems.

To install Git, we could use this guide located on the progit or also you can see this page which explains how to use textmate with git

We set git configuration:

$ git config --global user.name "Your Name"
$ git config --global user.email youremail@example.com

There is a great Quickstart for using Heroku which I used as a base for this post: http://docs.heroku.com/quickstart

  • Sign in in Heroku
  • Install Heroku gem:
$ sudo gem install heroku
  • Create the local application in your mac: rails myapp
  • Access to the rails app: cd myapp
  • Install git
  • Execute git:  $ git init
  • Do git add:  $ git add .
  • We access to the following command:
    • Do git first commit: $ git commit -m "new app"
    • We open the application, and we start the local server ruby script/server and access to localserver using http://127.0.0.1:3000
    • As usual, we generate a index or home controller. I generally call them dashboard as it is sexy: $ ruby script/generate controller dashboard index
    • We delete the entry page: $ rm public/index.html
    • We modify the config/routes.rb to enter the following route map:
      • We create the heroku application directly on the heroku site from our computer merely using the Heroku’s gem
      • Now the web site will be visible on the following address: http://severe-stone-45.heroku.com. Sustitute the name by the name provided by Heroku and you got it. As the heroku repository is blank when we create the application we need to deploy the code to a specific branch, we deploy the code throuh this instruction
    • $ rake db:create
      db/development.sqlite3 already exists
      map.connect ':controller/:action/:id'
      map.connect ':controller/:action/:id.:format'
      # Enter the route to access to enter the dashboard
       map.root :controller => "dashboard"
      rake db:migrate
      heroku create
      Created http://severe-stone-45.heroku.com/ | git@heroku.com:severe-stone-45.git

      $ git push heroku master

    Categories: Ruby, RubyonRails Tags:

    I have changed to JQuery in Rails

    November 8th, 2009 admin No comments

    jQuery is today the best js library, prototype is a challenger.The reasons why I think this are beautifully illustrated on the following post. To use jQuery in rails install the following plugin:

    ruby script/plugin install http://ennerchi.googlecode.com/svn/trunk/plugins/jrails

    Here is a list of existing functions which are available once we replace prototype+scriptacuolous for the jquery. Hopefully, this support will improve once we approach to Rails 3.

    If you want to use both libraries, you will keep prototype js files, if you plan to use only jquery you could removed them. I particularly think that seems you have decided to use jquery there is few reasons to keep them.

    Also, there are two ways to use jquery, I just found this interesting article which speak about a different way to use jquery, not using jrails but instead in a more unobstrusive way. Interesting point of view.
    http://www.notgeeklycorrect.com/english/2009/05/18/beginners-guide-to-jquery-ruby-on-rails/

    Kind regards and good weekend

    Conferencia Rails 2008

    November 14th, 2008 admin No comments

    Un más ActivoRicordi ha estado en la conferencia Rails española. Un año más esta siendo una gran experiencia, un año más el software es la excusa para juntar gente brillante sobre un mismo techo y compartir que se esta haciendo cosas muy interesantes en este país relativos a la innovación.

    Muy lentamente se esta generando un tejido empresarial de innovación y productividad a través de la technologia “Ruby on Rails” y a su alreador. Una technologia que es la excusa para lanzar iniciativas con muchos puntos comunes

    Colaboración y comunidad: Las aplicaciones son esfuerzos colaborativos de un grupo de personas buscando situaciones win-win.

    Usabilidad : Simplicidad de uso en las interfases, flexibilidad o más bien adaptación a los usuarios.

    Productividad: Crear desarrollo productivos, competir con inversiones pequeñas con los jugadores más grandes

    Software como servicio o con servicios añadidos: El software se convierte en algo más que una licencia, es la excusa para proporcionar un servicio al usuario, flexible, agil y adaptado a sus necesidades.

    Estandarización: Enlazado con la colaboración, utilización de estandares.

    Escalabilidad: La infrastructura no debe convertirse en una limitación a las ideas y a los proyectos.

    Sin embargo, considero que este será uno de los años claves para Framework, por un lado empiezan a aparecer competidores en el mercado como Merb que ganan adeptos, y por otro la crisis obliga a muchos proyectos a darse una dosis de realidad.

    Aunque existen casos de exitos muy interesantes, me ha sorprendido mucho saber que “La Razon” corre sobre Rails, y si sigue a este ritmo “La Coctelera” pronto será conocida como “La Incubadora” : UVLog, iwannagothere.com , estos tipos no paran de crear propuestas nuevas.

    Cierro aquí para asistir a la Keynote de “Obie Fernandez”.

    Hasta el proximo año!!

    Tutorials in Routing in Rails 2.0

    August 29th, 2008 admin No comments

    Create an AddressBook 1

    August 26th, 2008 admin No comments

    Hi All:

    One of the things I dislike most of Open Source Applications, it is that are very difficult to continue since the code and way it is built, also it does not cover components; instead of building new entire application I would like to see how to build small reusable components which could be integrated on new applications. Today, we are going to explain how to create a slik “address book”.

    1) Create the rails project:

    As I am a fan of mysql database, I do create projects specifically for this database with the sentence:

    rails -d mysql addressbook

    2) Create main objects:

    The base of the addressbook is the contact object which we are going to scaffold:

    script/generate scaffold contact firstname:string lastname:string lastname2:string phone_id:integer address_id:integer photo_id:integer page_url:string title:string company_id:integer email_id:integer background:text comments:text author:string

    As you can see the Contact is compound by other objects such as phone, address and photo. These objects are formed by several characteristics:

    • firstname
    • lastname
    • lastname2 – For those countries where a second last name is used
    • phone_id – Each contact can have multiple phone which forms an array of values
    • address_id- The address could be multiple and build on an object with an array of values
    • comments – It has an auto-complete feature

    3) Create authentication:

    We are going to create the authentication, so only authorized users can access to the application

    script/generate scaffold user userName:string firstName:string lastName:string alias:string email:string password_salt:string password_hash:string

    4) Setup the database:

    We open the database.yml file where we insert the password of the root user or if we have leave it blank as default we do not have to enter it. In order to look it, install a mysql administration tool. There are plenty on the Internet.

    We execute the rake command to create the database

    rake create:db:all

    And we create the first migration

    rake migrate:db

    Now we have created the contact object on the database.

    On next chapter, we will create the rest of the subornidates objects and we will add plugins.

    MacOS X Ruby on Rails Development tips I

    August 14th, 2008 admin 1 comment

    We open a set of posts dedicated to mentioned Rails development tips or tricks which are often found in several articles:

    1) Open several instances of a webrick server from the command line on MacOs X Leopard :
    This article is based on a similar tip provided for Windows OS by Mr. Arjun Ghosh. It is basically the same.
    a) I open my Terminal app
    b) I access to my rails application directory (previously created) which is created on my Library directory:
    cd library/rails_apps
    c) Then, we access to each one of the applications we want to open in webrick: We open the first server with the typical sentence:
    /script/server
    and then if we want to open another application, we access to the application:
    cd
    /script/server -p3001

    2) Scaffold Rails 2.0

    Clearly, I do not understand this scaffold change on the Rails 2.0 version, it has changed one of the features I enjoyed most from Rails which was a great dynamic scaffolding, and also the possibility to scaffold a model and a specific controller. I understand that it is being done to obtain a more Restful approach on the models and on the controllers, but sometimes is a pain.

    Not long time before the appearing of Rails 2.0, I had the brilliant idea of buying last version of version of the Rails book which obviously have all example written in Rails 1.x version. For that reason depot example is no longer valid.

    As Mr. Arjun Ghosh mentioned on his comment before there is a new edition of “Agile Web Development with Rails” coming out soon. (See reference)

    Enough for now
    Regards

    Aplicación para administración de fincas

    December 30th, 2007 admin No comments

    He encontrado por casualidad una aplicación web para administradores de fincas y comunidades que se llama eFinca 2.0. Se trata de un proyecto o un negocio realizado por dos programadores de Ruby on Rails.

    Uno de ellos Vicent Gozalbes tiene un blog bastante interesante con un montón de recursos sobre Ruby on Rails.

    Feliz Año 2008 a todos

    Gestión de autorizaciones y autentificaciones en RoR 2

    December 2nd, 2007 admin No comments

    2. Una vez creados asignaremos las rutas restful dentro de la carpeta config/routes.rb
    Abrimos el fichero config/routes.rb, y introducimos las siguientes entradas:

    map.resources :usersmap.resource  :account

    Para mapear los controladores vamos a utilizar las siguientes URLs para mapear la autentificación:

    
    
    map.signup '/signup', :controller => 'users', :action => 'new'
    map.login  '/login', :controller => 'account', :action => 'new'
    
    map.logout '/logout', :controller => 'account', :action => 'destroy'

    3. Permitir a los propios usuarios mantener sus detalles una vez registrados, tenemos que incluir el siguiente código al controlador que gestiona como hemos visto la autentificación de los usuarios.

    En el caso de que hayamos creado un controlador denominado “account” y un modelo denominado como “user”, abriremos el fichero “account_controller.rb” dentro de nuestra carpeta de “app/controller” . Abrimos el fichero ‘<nombrecontrolador_controller.rb‘ y le añadimos el siguiente código:

    ## Edit User## allow a user to edit their detailsdef edit
    
    @user = User.find(self.current_user.id)
    
    end
    
    
    
    ##update the user table
    
    def update
    
    @user = User.find(self.current_user.id)
    
    if @user.update_attributes(params[:user])
    
    flash[:notice] = 'User was successfully updated.'
    
    redirect_to :action => 'index'
    
    else
    
    render :action => 'edit'
    
    end
    
    end
    
    end

    Una vez añadido este código al controlador vamos a crear las siguientes vistas, dentro del controlador ‘user’:

    _userForm.rhtml

    <%= error_messages_for 'user' %><!--[form:user]--><!-- all custom fields here -->
    
    <p><label for="user_email">Email Address</label><br/>
    
    <%= text_field 'user', 'email'  %></p>
    
    <!--[eoform:user]-->

    Y luego creamos otro recurso más denominado ‘edit.rhmtl’

    <p>Edit your details</p><%= start_form_tag :action => 'update' %><%= render :partial => 'userForm' %>
    
    <%= submit_tag 'Edit' %>
    
    <%= end_form_tag %>
    Categories: RubyonRails Tags:

    Gestión de autorizaciones y autentificaciones en RoR

    December 2nd, 2007 admin 1 comment

    Una de las mejores cosas que tiene “Rails” es lo sencillo que es gestionar todas las autorizaciones y la autentificación de los usuarios además de la razonable cantidad de “plugins” ya escritos. En cierta manera, aunque pueda parecer muy restrictivo sería genial que estuviese contenido ya dentro del mismo “framework” como un gestor de usuarios, roles y grupos.

    De cualquier manera existe ya un plugin denominado RESTful Authenticated (versión nueva del Act_as_Authenticated) que nos ahorra mucho trabajo y que fácilmente podemos adaptar para administrar el resto del sistema de autorizaciones y autenticación.

    1.Obviamente lo primero que hemos de hacer será instalar el plugin “RESTful authentication” en nuestra aplicación, se trata de un paso sencillo.

    2.- Autentificación del Usuario:

    RESTful authentication” es un generador que nos va permitir crear el modelo y el controlador que va a realizar la gestión de la autentificación del usuario.

    ruby script/generate authenticated user account
    rake db:migrate
    Si estamos utilizando RadRails, iremos a la pestaña de Generators una vez bajado e instalado el plugin, y introduciremos “authenticated” dem
    ‘user’ es el nombre del modelo que vamos a utilizar para guardar los datos de autentificación del usuario, además creamos el nombre del controlador que va a gestionar la autentificación en este caso vamos a llamarlo ‘account’, pero podemos llamarlo ‘cuenta’,'acceso’ o el nombre que le queramos dar.

    ./script/generate authenticated <usermodelname> <controllername>

    ./script/generate authenticated user sessions

    Esto no creara un modelo ‘user’ o ‘usuario’ y un controlador que se denominara ‘account’ en que luego entraremos a para adaptarlo a nuestro intereses

    ./script/generate authenticated user account \–include-activation

    Mediante el generador se crearan automáticamente los siguientes recursos:

    exists app/models/
    exists app/controllers/
    exists app/controllers/
    exists app/helpers/
    create app/views/account
    exists app/controllers/
    exists app/helpers/
    create app/views/users
    exists test/functional/
    exists test/functional/
    exists test/unit/
    create app/models/user.rb -
    create app/controllers/account_controller.rb
    create app/controllers/users_controller.rb
    create lib/authenticated_system.rb
    create lib/authenticated_test_helper.rb
    create test/functional/account_controller_test.rb
    create app/views/users/new.rhtml
    create test/functional/users_controller_test.rb
    create test/unit/user_test.rb
    create test/fixtures/users.yml
    create app/helpers/account_helper.rb
    create app/helpers/users_helper.rb
    create app/views/account/new.rhtml

    Si se utiliza el textmate existe un bundle especifico dentro del textmate que permite la instalación de plugins.