RoR


Simple reference for creating a Rails migration

I keep forgetting the rails generator syntax for migrations :X  I can never find just a quick easy guide for it – so I thought I’d write one up!

Instructions

  1. cd …
    obviously first make sure your in the main project folder in the console
  2. export RAILS_ENV=environment
    Also, make sure you’re in the right environment, you will probably want to make the change first in your test or development environment and then put it to production
  3. rails g migration AddColumnToModel column_name:column_type
    Here’s the main part, on  older versions rails g migration will be script/generate migration.  The “AddColumnToModel” syntax is important and should relate to the migration you’re making like “AddEmailToUser” and then at the end you can add a “column_name:column_type” reference for each column you want to add, for instance with the last example you would put “email:string
  4. rake db:migrate
    run the migration and add those columns to the database!  You’ll probably want to review the migration that was generated first though – it’ll be the latest file in the …/db/migrate directory

AND MAKE SURE TO RESTART YOUR SERVER AFTER MAKING A CHANGE

Column Types

  • binary: for files/ data blob
  • boolean: true/false
  • date: only date: (year, month, day)
  • datetime: date + time
  • decimal: precise decimal numbers – for when math neds to be accurate
  • float: decimal numbers
  • integer: whole numbers
  • string: 255 max alphanumeric characters
  • text: unlimited alphanumeric characters
  • time: only time (hours, minutes, seconds)
  • timestamp: same as datetime

 

And, if you make a mistake a quick way to go back and fix it is “rake db:migrate:redo” that will undo your last change, and re-run it.

Also, if you want to only run “rake db:migrate:up VERSION=20090408054532”

In a pinch you can also run a migration by hand in the console with the following format:
ActiveRecord::Migration.add_column :table, :column_name, :column_type

References:
http://stackoverflow.com/questions/11889048/is-there-documentation-for-the-rails-column-types
http://stackoverflow.com/questions/15162055/rails-generate-migration
http://stackoverflow.com/questions/7694487/ruby-on-rails-how-can-i-revert-a-migration-with-rake-dbmigrate

Permalink » No comments

Social Login with Phonegap, Omniauth, Tokens, and InAppBrowser

For a project I needed to integrate Facebook and Twitter logins to a phonegap app.  I went through a ton of plugins and jsOAuths, but they were all quite cumbersome. I really wanted a simpler approach that would handle Twitter and Facebook at the same time.

This article about Twitter integration with Child Browser got me started in the right direction.  It’s a little dated with Child Browser, so I set out to update it to work with InAppBrowser, but during the process I realized that I could actually handle this issue a lot simpler.  Mostly because I only needed to login and didn’t require any deeper integration with Social platforms.

So after a little more digging I came across this lovely article on cross window communication with InAppBrowser which was everything I needed to take care of business!

In my case, the server is going to be doing all the heavy lifting, and for this project we already had Omniauth set-up for social login and tokens so I only needed to make a few tweaks to get this rolling.

The first tweak was to get it to output JSON for the App.  Out of the box Omniauth will keep track of your params, so I made it return a JSON response when I requested it in the query string like so “/users/auth/facebook?json=true”

Just for example, here how it would look if you were using the standard facebook action for omniauth:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def facebook
    @user = User.from_omniauth(request.env["omniauth.auth"])
 
    if @user.persisted?
      sign_in @user, :event => :authentication #this will throw if @user is not activated
    else
      session["devise.facebook_data"] = request.env["omniauth.auth"]
      return redirect_to new_user_registration_url
    end
 
    return render :json => current_user if request.env["omniauth.params"]["json"]
 
    set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
    redirect_to "/"
  end
end

The important parts here are:

  • I’m using “sign_in” instead of “sign_in_and_redirect” so I can handle the redirection later down the line.
  • Then I’m adding in “return render :json => current_user if request.env[“omniauth.params”][“json”]” so the callback will output the current user in JSON.

In my case the JSON output for current_user includes a token I can use to integrate with the API.

With that all set you’re ready to capture that JSON in phonegap:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
win = window.open(base_url+'/users/auth/facebook?json=true', '_blank', 'location=yes,enableViewPortScale=yes');
win.addEventListener('loadstop', function (e) {
  if (e.url.indexOf(base_url) >= 0 && e.url.indexOf('callback') >= 0) {
    win.executeScript(
      { code: "document.body.innerHTML" },
      function(values) {
        r = values[0];
        r = r.replace(r.substring(0, r.indexOf('{')),"").replace(r.substring(r.indexOf('}'),r.length).replace(/}/g,''),"");
        r = jQuery.parseJSON(r);
        //now r.api_token is available to use however you need in your app
        win.close();
      }
    );
  }
});

This works by:

  1. First opening a window with the social login page “/users/auth/facebook?json=true
    on my app base_url is the domain of the API, like http://api.google.com for example.
  2. Next I’m listening for every-time the page in InAppBrowser finishes loading with “addEventListener(‘loadstop‘”
  3. Then I’m waiting for the URL to have my API’s domain name plus “callback” here “if (e.url.indexOf(base_url) >= 0 && e.url.indexOf(‘callback’) >= 0) {
  4. Once there I use “executeScript” to fetch the document body, which is returned as values[0].
  5. Then I clean the return value of any HTML using replace and substring, then parse that to JSON

After that you can use that token in your App however you need to integrate with your API.

Permalink » No comments

Ruby, Haml, and SASS in Dreamweaver CS6

Call me a dinosaur, but I’m still chugging away with Dreamweaver.  I can’t pull myself away from the lovely site management and built in FTP features 🙂

But Dreamweaver lacks support for Ruby, and it’s friends HAML and SASS 🙁  I’ve never gotten HAML and SASS to work 100% with highlighting, but there’s a nice little extension for getting ruby highlighting called “Rubyweaver.”

How can download Rubyweaver from github, https://github.com/cannikin/rubyweaver.  At this time it doesn’t have installation instructions, but I just sent a pull request containing them, so they will probably be there now 🙂  It’s pretty simple, just make certain not to skip the “Run as administrator” step, or the installation won’t take.

Now you can open up ruby files and they’ll have some lovely color coding 🙂  Next, is to make dreamweaver open SASS and HAML files.  There are some tricky steps to get syntax highlighting for SASS, but everything I’ve tried just makes everything pink.  That only really works if you write SASS the same way as you would write CSS.  (I indent my SASS – no curly braces for me!)

In Dreamweaver

  • Go to file>preferences
  • Select File Types/Editors
  • In “Open in code view” add ” .haml .sass”

In notepad

  • Go to C:\Users\~Your Username~\AppData\Roaming\Adobe\Dreamweaver CS6\en_US\Configuration
  • open Extensions.txt
  • on the first line add in ,RB,HAML,SASS
  • change
    HTM,HTML,HTA,HTC,XHTML:HTML Documents
    to
    HTM,HTML,HTA,HTC,XHTML,HAML:HTML Documents
  • and then change
    CSS: Style Sheets
    to
    CSS,SASS:Style Sheets
  • You can also add any other extensions you need to wherever you want.

Now they’ll open up in code view and you’ll be able to search whole folders as well. 🙂

Permalink » No comments

Rails for Zombies

I recently completed the Ruby on Rails tutorial “Rails for Zombies.” I really like it’s “edutainment” zombie filled format, and on top of that it’s a very well written and easy to follow tutorial.

The tutorial consists of five “chapters.” Each chapter is broken up into an approximately 10 minute video and then a lab portion where you get to do exercises related to the video.  It’s really great to try out the code right after hearing about it, and I like that it doesn’t get drearily technical at the get go with needing to get Rails up and running.  A lot of RoR tutorials start with installing and runing your own local server, which a least for me is the least pleasant part.

A nice take away is the free PDF download it offers, which has all the slides from the video and is a nice reference back to everything you learned from the tutorial.  You also get a coupon for some paid rails tutorials after you finish.  They have “Rails for Zombies 2” in the works so I’m thinking of saving it for that :3

At their Code School website they also offer a “Rails best practices” class which sounds a little advanced for diving into right after Rails for Zombies, but if it’s anywhere as well put together as Rails for Zombies I’d like to come back to it later.

http://railsforzombies.org/

Permalink » No comments

Try Ruby

I’m trying to come to grips with Ruby on Rails, and the website Try Ruby was suggested to me.

It was a really impressive online tutorial set-up as a user prompt.  I really appreciate that it’s one Ruby tutorial that doesn’t require me to be download and installing packages willy-nilly to get started 😛  It’s extremely newbie-friendly and is well written and utilizes some light humor to help you get through it 🙂  I think the last chapter was a bit clumsy…but may have just had one too many typos along the way.

Regardless, I’d say the “15 minute” bit is no lie and well worth the time if you’re trying to get better acquainted with Ruby or RoR such as myself.

http://tryruby.org/

Permalink » No comments