• Shortcuts : 'n' next unread feed - 'p' previous unread feed • Styles : 1 2

» Publishers, Monetize your RSS feeds with FeedShow:  More infos  (Show/Hide Ads)


Date: Monday, 10 Jun 2013 23:02

I typically like to assign shared select items with negative ID values.  This post describes using negative ID values for a selection of stores or coupon types, where "Manufacturer's Coupon" and "Other" have negative values.  Here's a screenshot from that post.

We're going to want our Stores SQL table to include -1: Manufacturer and -2: Other records which brings us to the subject at hand, reassigning SQL Auto_Increment ID Values in Rails.  When I searched on this the typical response was something along the lines "run rails script/dbconsole and change the records directly." Technically that answer is correct, but this post will demonstrate walking through the process.

In Development

In Development we're probably using Sqlite3.  We'll edit our application SQL tables by entering "rails dbconsole" at the root of our Rails app.

For our demonstration we're going to change an Auto_Increment field in a scratch app's Users table, changing user with ID "70" to and ID of "-1."  We're in dbconsole and will edit the existing record's ID with a SQL statement.  For those of us coming out of the SQL Server world, we don't have to set AutoIncrement Off or anything else in Sqlite, PostgreSQL or MySql. Just update the record.

Done!  Here's the result.

On Heroku

What about on a public-facing site like on Heroku.  Heroku uses PostgreSQL, so we'll need to install PostgreSQL on our Linux Mint box (what, you're not running Linux Mint? :)  That gives us the ability to use pg:psql to update our application database on Heroku as easily as we updated our local Sqlite database earlier.

$ heroku pg:psql

We'll do a direct sql update and view our results. Bam!  Auto_Increment ID values updated!

Author: "--" Tags: "Ruby"
Comments Send by mail Print  Save  Delicious 
Date: Saturday, 08 Jun 2013 23:37

Learning Rails 3 by Simon St. Laurent and company is available from O'Reilly with a 4.3 out of 5 star rating. It's a good book for beginners and anyone else who wants to relax reading about rails. Here are highlights I found interesting, along with sample code excerpts to serve as a quick reference and to give you an idea of what you can read more about by purchasing the book.

pXI. There's a lot of seemingly magical behavior in Rails that works wonderfully -- until one of the incatations isn't quite right and figuring out what happened means unraveling all that work Rails did. Rails certainly makes it easier to work with databases and objects without spending forever thinking about them, but there are a lot of things to figure out before that ease becomes obvious.

p36. If there is a layout file in /app/views/layout that has the same name as a view, Rails will use that instead of application.html.erb.

p120. The after_save method is one of several callback methods support by ActiveRecord. Note that there are after and before methods for create, destroy, save, update, validation, validation_on_create, and validation_on_update.

p119. Chapter 8. Examples of using Form Builders.  <%= form_for(@person... :builder => TidyFormBuilder) do |f| %>

p141. Passing block to collect() on building a Select.

<div class="field">
   <%= f.label :student_id %><br />
   <%= f.select :student_id, Student.find(:all , :order => "family_name,
       given_name").collect {|s|
          [(s.given_name + " " + s.family_name), s.id]} %>
</div>

p161. A convenience method checks to see whether a given student is enrolled in a specified course:

def enrolled_in?(course)
   self.courses.include?(course)
end

The enrolled_in? method uses the include? method of courses...

A similarly useful convenience method returns the list of courses that a student is not yet enrolled in, making it easy to create logic and forms that will let them enroll:

def unenrolled_courses
   Course.find(:all) - self.courses
end

This one-liner does some tricky set arithmetic

p176. Migrations are effectively lists of changes. Each migration is a set of instructions that applies to the results of the previous migration.

p177. Using Rails Console. You can use the y method (for YAML, a convenient data exchange format):

ruby-1.9.2-p136 :005 > y student
--- !ruby/object:Student
attributes:
id: 2
given_name: Milletta
middle_name: Zorgas
...

Also examples on using the app convenience object in IRB and includes.

> include Rails.application.routes.url_helpers

Then you can do things like:

> new_course_path
=> "/courses/new"

> app.get "/students/2"
=> 200 (for successful request)

> app.controller.params
=> {"action"=>"show", "controller"=>"students", "id"=>"2"}

> app.response.body
=> "<!DOCTYPE html>\n<html>\n<head>\n <title>Students
</title>\n <link href=\"/assets/application.css?body=1\" media=\"all\"...

> app.headers
=> {"Content-Type"=>"text/html; charset=utf-8", "X-UA-Compatible"=>"IE="...


p195. Example of using the debugger in IRB.

p260. You might have a route that looks like:

match ':action/awards', :controller => 'prizes'

if Rails encountered a URI like:

http://localhost:3000/show/awards

Then it would route the call to the show method of the prizes controller.

Also on p260, example of Globbing.

p266. Something I personally use all the time: rake routes | grep something...

p276. Example of nested CSS and the use of variables in SASS. Advises removing *= require_tree from application.css.scss file and using the @import directive on the files you specify to share all the variables, mixins and nested CSS of imported style sheets.

p282. Sprockets is a library that began shipping with Rails 3.1 for compiling and serving web assets like JavaScript and CSS files. It also serves as a “preprocessor pipeline.” ...Sprockets gives rise to JavaScript and CSS becoming first-class citizens, all because of that preprocessor pipeline it adds to a Rails application.

p286. On Bundler and Gems. Even Rails itself is a gem—you remember running “gem install rails,” right?

p293. CoffeeScript is a programming language, written in CoffeeScript, that compiles into JavaScript. Similar to the universal translator, you can write CoffeeScript code that is “translated” to JavaScript. If you’ve written JavaScript code, you’ll instantly see CoffeeScript’s appeal: it can spit out JavaScript with about one-third less code, it runs fast, and the clean syntax is similar to Ruby’s beautiful code.

Author: "--" Tags: "Ruby"
Comments Send by mail Print  Save  Delicious 
Date: Saturday, 08 Jun 2013 16:04

David Chelimsky’s The RSpec Book: Behaviour Driven Development with RSpec, Cucumber, and Friends (The Facets of Ruby Series) covers one of my favorite areas of Rails development. I thought I’d share some highlights for you if you haven’t read the book (and as a quick reference for me.)  Since I read the book on Kindle I’ll be providing the Location rather than page numbers.

2138 This is the BDD cycle. Driving development from the outside in, starting with business-facing scenarios in Cucumber and working our way inward to the underlying objects with RSpec.

4374 Behaviour-Driven Development is about implementing an application by describing its behavior from the perspective of its stakeholders.

Using the SMART approach in software delivery. Each area is defined on 4431 The acronym SMART is used to describe outcomes or objectives that have certain characteristics, namely, that they are Specific, Measurable, Achievable, Relevant, and Timeboxed.

I like the idea of wrapping a class in a test module for report clarity. 4633. If User is in the Authentication module, we could do something like this:

module Authentication   describe User, "with no roles assigned" do

The resulting report would look like this:

Authentication::User with no roles assigned

On using “context.” 4652. The output would be the same as when we used describe on the second line, but context can make it easier to scan a spec file and understand what relates to what.

4777. Example on using “pending” to stop execution.

4794. Wrapping test code in a Pending block. Block is executed and raises a PendingExampleFixedError if passes.

5063. Including shared modules in RSpec Configuration.

5629. array.empty?should == true expresses our intention, but array.should be_empty is better.

5634. RSpec overrides method_missing to provide this nice little bit of syntactic sugar. If the missing method begins with “be_,” RSpec strips off the “be_” and appends “?”; then it sends the resulting message to the given object. Ex: user.should be_in_role("admin") / user.in_role?(“admin”)

6271. For literal values, we can just pass them directly to the with method: account_double.should_receive(:withdraw).with(50)

6750. RSpec ships with adapters for Mocha, Flexmock, and RR mocking frameworks.  Add in RSpec Configuration config.mock_with <framework_id>

6984. Adding RSpec options like –color and –format documentation in ~/.rspec.

7048. RCov – code coverage tool, observing what code in your application that was never executed when you ran your specs with a percentage of code base covered by specs.

7304. Creating custom matchers. Ex: joe.should report_to(beatrice)

7569. RSpec formatting options.

7629. A common understanding of done is crucial to the success of any project. How do we know when we’re done if we can’t agree on what done means? Such agreement is pretty easy to find in many kinds of projects. A cake is done when it reaches the right consistency. A building is done when the city inspector says it meets code. If we apply the right tests and they pass, we’ll know when we’re done. But with software, there’s a catch.

…Cucumber supports collaboration and communication between stakeholders and the delivery team. It uses a simple language for describing scenarios that can be written and read with ease by both technical and nontechnical people. These scenarios represent customer acceptance tests and are used to automate the system we’re developing.

9453. Using save_and_open_page to capture scenario response at any point and open it as a static HTML file in the browser.

11445. In his article “Skinny Controller, Fat Model,”[63] Jamis Buck recommends pushing business logic down to the model, keeping views and controller actions lean. This guideline helps us to follow the Single Responsibility Principle by keeping controllers and views focused on application logic and keeping the models focused on business logic.

Author: "--" Tags: "Ruby"
Comments Send by mail Print  Save  Delicious 
Date: Thursday, 06 Jun 2013 23:53

Rails makes creating an HTML Select Control easy, but what about when you want to add custom options to the selection list? Also easy.  Let's look at an example of a Select list with not one but two additional custom options.

We have a Store Selection so we can can assign coupons to a store. But we also want to add two additional options: "Manufacturer's Coupon" at the top of the list and "Other" at the bottom.

On new coupons we want the default selection item to be "Manufacturer's Coupon."  The Manufacturer's Coupon has an ID of -1 and here's where we'll set that in the controller.

Now for the HTML.  We're going to invoke the { |s| [s.name, s.id] } block for each element of our stores array to generate our user's stores using the Ruby collect() method.  Before and after the array we're adding our custom options as nested arrays.

More Select Option goodness can be found on the RailsGuides Form Helpers page.

Author: "--" Tags: "Ruby"
Comments Send by mail Print  Save  Delicious 
Date: Friday, 31 May 2013 22:59

Here's the setup. We have a Store Controller which allows all actions except Edit, so we want to ensure that Store#Edit is not a valid route. Another way of stating our intention is that we're testing for a No Route Matches.

Here's what it looks like in routes.rb where Store is a nested resource of Users.

resources :users do
    resources :stores, only: [:index, :new, :create, :destroy]
    resources :coupons
end

Here's our RSpec method located in our stores_controller_spec.rb file.

describe "GET 'edit'" do
  it "should not be routeable" do
    expect(:get => "/users/1/stores/1/edit").not_to be_routable
  end
end

We're using RSpec's be_routable matcher. Here's a good be_routable reference on Relishapp.

It would be nice to write the expectation in a more Ruby-esque fashion, perhaps

expect(get :edit, :user_id => user.id, :id => 1).not_to be_routable

but as far as I know we have to enter a string path. Otherwise, since Rails doesn't know about the route we'd get a NoMethodError. We could test for the error, of course, but be_routable seems cleaner.

Author: "--" Tags: "Ruby"
Comments Send by mail Print  Save  Delicious 
Date: Thursday, 30 May 2013 00:13

There are multiple ways to present dates in a Rails form. The default approach when scaffolding an object is to present the date as 3 dropdowns for date year, month and day.  How to generate a test with Capybara in RSpec isn't always obvious, so we'll going to cover that here.  We're also going to show how to style the html a bit, since that is not obvious either.

Here's a date selection in a rails form.

The Controller

We're working with coupons in this form, you know, $1.00 off a 9-pack of Charmin.  Coupons have a belong_to relationship with User, who has_many coupons. While our main focus is on testing the date selections in Capybara and RSpec, a quick visit to the controller's CREATE action may provide a helpful processing tip.  Coupon, as we just mentioned, belongs to Users.  It may be initially confusing how we're going to extract the form contents of this nested resource.  The trick here is to first define the @user object then use it to build the @coupon from the form parameters.

Testing in Capybara and RSpec

Now onto the tests. It would be nice if you could do a simple

select "Expiration Date", from: "coupon_expiration_date"

but you can't. The key here is to select the date values from the individual dropdown selections.

As you can see we just selected the selection.text. If you want the selection.values, here's a way of retrieving those.

Hm, I suppose find_field(...).text would work for the text items, but I haven't tested that.

Html Stylings

If you're interested in how the dropdowns are styled it's okay since that isn't obvious either.  To shorten the width of the date element dropdowns we're passing the CSS class to each of them.

<%= f.date_select :expiration_date,
   {:order => [:day, :month, :year], :start_year => 2013, :end_year => 2015},
   { :class => 'date-select'}  %>

I don't plan on staying with the multiple date-part selection approach on the Coupon form indefinitely, so there will no doubt be a future blog post titled Alternatives to the Default Rails Date_Select, or something along those lines...

Author: "--" Tags: "Ruby"
Comments Send by mail Print  Save  Delicious 
Date: Saturday, 25 May 2013 18:23

Here's our scenario. We have Users who can create and manage a list of stores like Kmart and Kroger's.  Store is a nested resource of Users with a path of

/users/:user_id/stores

Our objective is to make sure a user with user_id 15 cannot load /users/37/stores and muck with user 37's store list. Exclusive Current_User access to prevent a really bad day for the web support group.

The Controller

To ensure that only a user with user_id 37 can load /users/37/stores and its actions we'll specify two access requirements in the StoresController. 1) the user must be signed in and 2) the correct user is the current_user having the :user_id in the path.  We do that with :signed_in_user and :correct_user.

:signed_in_user is located in sessions_helper.rb

:correct_user is a private method in the controller.

The Rspec Tests

Okay, that should do it, but what will the Rspec tests look like?  We'll create two users, :user (our current user) and :other_user. The key is using a controller stub to assign the controller's :current_user with our valid user. Then we access a controller action with other_user, at which point, because of our StoresController :correct_user method we should be redirected to the home page.

Using Shared_Examples_For

As a sidebar, we're also using a shared_examples_for group to make our tests more DRY, passing each controller action as a parameter. 

It's good to know that User 37's store list is now secure!

Author: "--" Tags: "Ruby"
Comments Send by mail Print  Save  Delicious 
Date: Friday, 24 May 2013 01:14

Sometimes you need a longer subject to describe a post, so even though the current subject is already long, here's a better one: Using a Boolean Column in a SQL Has_Many Through: Table to Retrieve Filtered Collections in Rails. 

Here's the scenario.  We have Users and we have Stores, with Users having many Stores through a lookup table called User_Stores. User_Stores (our Rails UserStore class) contains user_id and store_id foreign keys to their respective tables. We also have a boolean column named "active" in User_Store that we want to use to display the User's Active Stores by default and optionally all of their stores.

A picture is always best, so here's the relationship breakout.

Our Model

Nothing much to report here other than establishing the usual has_many and through: relationships between Users and Stores. The two applicable models with configuration code for our purposes being User and UserStore.

With our has_many and through: relationships established we can retrieve a list of stores with

@stores = @user.stores

Active Stores Verses All Stores based on the UserStore.Active flag

We've arrived to the central issue, retrieving all stores or active stores only based on the boolean "active" field in the UserStore lookup table. We can make this hard or simple.  I wrote this post because I spent too much time making this hard when it turned out to be simple. My problem was that I was thinking in terms of creating a new class and new relationships. In reality we needed little more than a new method.

Let's start at the end and show how we display all stores and active-only stores in the Controller.  Keep in mind that Stores belongs to User.

class StoresController < ApplicationController
before_filter :signed_in_user

  def index
    @user = User.find(params[:user_id])
    @stores = @user.active_stores
  end

  def all
    @user = User.find(params[:user_id])
    @stores = @user.stores 
  end

We're displaying active-only stores by default at /users/[user_id]/stores and added a new route and method to display both active and non-active stores at /users/[user_id]/stores/all.

The Method

And for the million dollar question (okay, the "ten buck question"), where did the @user.active_stores come from? This is a new method we added in our User Model.

def active_stores
  self.stores.where(:user_stores => {:active => true})
end

The Route

One more thing to do, add a route in our /config/routes.rb file.  We'll match up a new stores/all path with the "all" method in our StoreController.

match 'users/:user_id/stores/all' => 'stores#all',
    :as => :user_stores_all, via: :get

Hope this helps someone who looks at creating dynamic collections based on a flag column in a lookup or "through" table as something more difficult than what it is.

Author: "--" Tags: "Ruby"
Comments Send by mail Print  Save  Delicious 
Date: Wednesday, 22 May 2013 23:39

Gimp is the standard bearer of high-end graphic design in Linux and it's a seriously beefy application. However, if you've spent years in Photoshop and Windows like I have, warming up to Gimp in Linux might take a bit of extra effort. I hope you believe as I do that the more you work with Gimp the more you will feel like that effort was worth it.

With that in mind, let's take some effort out of moving selections and paths.

Moving Selections

By "moving a selection" I'm referring to moving a selection's content, not the selection area itself. In Photoshop this is a simple Shift-Click affair and in Gimp, well, it isn't. Here is an example of a moved selection.

The secret to moving selections in Gimp is to first "float" the selection to it's own Floated Layer, at which point you can press "M" to move it along with its content.  My Gimp custom keyboard setting for floating a selection is CTRL-SHIFT-L.  Followed up by "M" for move.  Speedy.

Moving Paths

It would also be nice if we could easily move paths as well. Below we see a path enhanced with the Gimp Draw Arrow Plug-in from the Gimp Plug-in Repository.  The arrow looks fine, but it's pointing in the wrong direction and not exactly where we want it.

A secret to moving paths is ensuring that they are on their own layer.  That way any move and rotate actions will move the path (along with the layer.)  A possibly better approach to moving paths is to first convert them to a selection with "Selection -> From Path" or SHIFT-V. Once the path is a selection we can use CTRL-SHIFT-R and rotate just the arrow.  We can also move it with "M" and either use arrows or the mouse.  I should note that is the path is not first in its own layer, you can use the float selection process we described above upon converting the path to a selection.

Here's the final result.  It might not be very pretty, but that doesn't take away from the satisfaction of being able to easily move stuff in Gimp.

Author: "--" Tags: "Linux"
Comments Send by mail Print  Save  Delicious 
Date: Wednesday, 22 May 2013 21:26

This is one of those "posts for me" where I want to document something so I don't have to think about it next time.  Today the thing I don't want to think about is updating Polly, a Twitter Desktop Client for Linux.  There are several Linux Twitter Clients available and I happen to like this one.  Here's a screenshot.

The app is written in Python and in active development, though you'll find some features like search not yet implemented.  The home page is at https://launchpad.net/polly

First thing we'll do to update to the newest version is download the tar.gz (current filename Polly-0.93.9 (pre-alpha 3.9).tar.gz.)  We can then extract it at the command line, but the quickest approach is to simply double-click and extract to a ~/Downloads subdirectory.  This is what the contents of the Polly subdirectory look like.

Here we want to go to the command line and NOT simply double-click on "Install", so we'll change into the ~/Downloads/polly subdirectory (let bash directory-complete help you) and run install as sudo.

~/Downloads/polly$ sudo ./install

Our new Polly executable is located in /usr/bin.  On my most recent upgrade I had an issue with Polly not launching.  If this happens to you the following terminal window should hold the key to a successful launch.

A couple of things to point out here.  You see circled that we're in the /usr/bin directory where we type "polly" and can discover our problem.  We're missing a module named "gdbm."  This is a Python module which Polly requires and can be installed with

$ sudo apt-get install python-gdbm

shown at the command prompt.

There, no thinking about upgrading when the next Polly alpha is released!

Author: "--" Tags: "Linux"
Comments Send by mail Print  Save  Delicious 
Date: Wednesday, 08 May 2013 16:00

If you do test driven development in Ruby on Rails you are probably familiar with running

$ rspec spec/whatever_spec.rb

at the command line where you'll see green or red, depending on the phase of the testing.  Guard is a Ruby Gem that automates running your tests and monitoring filesystem changes so that when we change a _spec.rb file only those tests get run.

And it gets better when adding Spork to the process. Rspec has to reload the entire Rails environment each time it runs. The Spork Test Server solves this problem by loading the environment once, then maintaining a pool of processes for running future tests.

The very best feature of Guard is that you get continuous testing feedback after adding the Notify Gems in your Gemfile.

# Notify and Test Gems for Linux
group :test do
    .
    gem 'rb-inotify', '0.8.8'
    gem 'libnotify', '0.5.9'
end

Here's a screenshot of Guard and Spork in action, providing RSpec Test feedback with Linux Mint Desktop Notifications at top right and all red-green details in the Terminal window bottom left.

I won't go into all of the configuration details, but to give you an idea of the setup required to enjoy continuous TDD feedback we

1) Add the Guard Gem and the Spork dependency to our Gemfile

group :development, :test do
  .
  .
  gem 'guard-rspec', '2.5.4'
  gem 'guard-spork', :github => 'guard/guard-spork'
  gem 'spork', '0.9.2'
end

2) Add the notify gems (shown earlier)

3) Initialize Guard so that it works with RSpec. 

$ bundle exec guard init rspec

This will also create our Guardfile which we'll want to modify so that Guard doesn’t run all the tests after a failing test passes.

4) We next bootstrap the Spork configuration with

$ bundle exec spork --bootstrap

and update our spec/spec_helper.rb to add environment loading. (not shown)

5) To configure RSpec to automatically use Spork we add the --drb option to our .rspec file

6) Rather than initializing Spork with Guard with

$ bundle exec guard init spork

we'll modify our Guardfile to initialize the Spork Server. (not shown)

At this point we can enjoy continuous testing feedback all day (and night) long!

$ guard

Yousa!

Author: "--" Tags: "Ruby"
Comments Send by mail Print  Save  Delicious 
Date: Friday, 26 Apr 2013 18:53

How many times have you heard people say that they need to keep a Windows PC around because they need it to do Quicken? I've heard it often. In fact, I'm one of those people, but I do not know for how much longer since I installed the very capable GnuCash on Linux Mint. Here's a screenshot of GnuCash, which you can see its checkbook function is nearly indistinguishable from Quicken.

You're probably wondering why this post is necessary. After all, if you want to install GnuCash or most other apps in Linux Mint you fire up the Synaptic Package Manager or you install it from the command like so.

$ sudo apt-get install gnucash

And both of those will fail, at least they did for me. GnuCash's installation messages were downright indignant, telling me to fix my broken packages before attempting to install GnuCash, that my libaqbanking33 resource was incapable of being updated, or some other nasty comment.

I did some digging into this and read some rather radical solutions, including re-installing the Synaptic Package Manager!  It turns out that you just need to know where to look for GnuCash, as the default Mint Software Repositories which usually doles out bits of pure joy will instead feed you GnuCash heartbreak.

We need to add GnuCash's primary respository to our software source list, archive.getdeb.net.  We do that with

$ wget -q -O - http://archive.getdeb.net/getdeb-archive.key | sudo apt-key add -

then

$ sudo sh -c 'echo "deb http://archive.getdeb.net/ubuntu quantal-getdeb apps" >> /etc/apt/sources.list.d/getdeb.list'

Notice the "quantal-getdeb" parameter.  Quantal is the respository key for Ubuntu 12.x versioned software, which is the equivalent of Mint 14's base code set.

You'll want to do a Package Update next with $ sudo apt-get update, after which you can perform a $ sudo apt-get install gnucash and hopefully have a much more positive experience than the last time you did it.

I haven't started playing with GnuCash, but I'll get back to you if I'm still one of those people who keeps a Windows PC around to run Quicken.

Author: "--" Tags: "Linux"
Comments Send by mail Print  Save  Delicious 
Date: Wednesday, 24 Apr 2013 14:34

If you are a happy Apache Passenger user you might lose some of that joy when your Rails site looks like this after an upgrade to Ruby 2.0.0.

This was particularly problematic for me since I had recently re-installed Ruby to reside in a personal home .rvm folder for Sudo Free Ruby with RVM.  So I was looking at both a Ruby reconfig and a possible upgrade incompatibility issue. I was seeing 404s when trying to view a Rails Route URi and endless missing Ruby Gem errors.  

Here's what I did to get the joy back, as my Passenger Apache Module is now properly handling Ruby 2.0.0 sites and using the Ruby Gems in my .rvm folder that it's supposed to be using. 

First I installed the latest passenger gem using the pre-release option.

$ gem install passenger --pre

Notice, no sudo.  Next I installed the latest Passenger Apache2 Module with

$ passenger-install-apache2-module

Again, no sudo.  As written in the Phusion Apache User's Guide, passenger-install-apache2-module is actually just a user-friendly front end around the command rake apache2, which performs the actual compilation of Phusion Passenger.  

When the Passenger Module compile is complete it will provide you with the Apache configuration you'll need to add to /etc/apache2/apache2.conf. Here's what that looks like.

When the output says /etc/apache2/apache2.conf, it MEANS /etc/apache2/apache2.config.  That's important, at least in my experience it is.  I plan on playing around with alternative Passenger load and configuration options for more Ruby Gemset version flexibility in the future, but I've found that if you put the Passenger config and load statements in their respective /mods-available/passenger .load and .conf files that Passenger will not load properly and throw up 404s on Rails Routes.

Hope this post restores Passenger and Ruby harmony for fellow Rail Folk after a Ruby 2.0 upgrade.

Author: "--" Tags: "Ruby"
Comments Send by mail Print  Save  Delicious 
Date: Friday, 19 Apr 2013 16:50

If you find yourself using sudo when installing and updating your Ruby Gems, sorry to have to be the guy to say it, but something is wrong with your Ruby setup.  But hey, it works, right?  Yes, but weirdness can result when gems are installed with sudo, and worse, your time is precious and it's being wasted when deep into a

$ bundle update

you have to start from the beginning because of a permissions issue on a particular gem requiring special attention.

I described how I installed rvm on Linux Mint and it was really really close to being accurate, but not quite close enough because to fix permissions issues on bundling I was typing

$ sudo gem install ...

to keep things rolling.

Then I discovered AJ ONeal's How to install Ruby (and RVM) on Ubuntu (for technotards.)  If you follow the technotard way like this technotard did, you shouldn't have to type sudo again, and you'll be on your way to flexible ruby development and versioned RVM GemSets.  Bundle updates should display successful completion with no sudo intervention each time, every time.

Author: "--" Tags: "Ruby"
Comments Send by mail Print  Save  Delicious 
Date: Wednesday, 17 Apr 2013 18:25

I recently came to the conclusion that I was spending too much time at the Linux Terminal command line navigating to my Rails Projects and knew there had to be a better way.  All of my projects have the path /mintland/webapps/[PROJECT]. Given that all project folders had the same root path, it should be easy.

I needed a script to change to any [PROJECT] directory allowing me to type something like

$ ./myproj.sh [PROJECT]

which would change to the project folder I entered as a parameter.

Bash changes directories in the script's subshell, so I also needed a solution that would take me directly to the project folder without entering

$ . ./myproj.sh [PROJECT] (or $ source ./myproj.sh [PROJECT])

Enter .bashrc, the Bash Shell script run each time a new terminal window (bash instance) is loaded.  I created two functions, rdir() which changes to the project directory, and rproj() which changes to the project directory and fires up Sublime Text.

rdir()
{
    webappDirectory="/mintland/webapps/"$1
    cd $webappDirectory
    clear
}

rproj()
{
    webappDirectory="/mintland/webapps/"$1
    cd $webappDirectory
    clear
    subl $1.sublime-project &
}

If the project folder name was "demo_app", the command to change into the project folder would be

$ rdir demo_app

You can see how the "demo_app" parameter is processed in the bash script with the "$1" input variable. 

If you're curious about the last line in rproj(), I use a [PROJECT].sublime-project file for each of my projects when loading Sublime Text, so when executed for our demo_app project example the line would be

subl demo_app.sublime-project &

Now THAT'S flexible directory navigation!

Author: "--" Tags: "Linux"
Comments Send by mail Print  Save  Delicious 
Date: Wednesday, 10 Apr 2013 15:52

After moving from Microsoft Windows to Linux I discovered that I now think more in terms of efficiency, of using the power of Linux to get the job done better and faster.  Most of us Linux geeks seem to always have a terminal window or two open, which means we spend a lot more time at the keyboard and less time with the mouse.

I found myself going back and forth between Chrome and a terminal window recently and knew there had to be a way in Linux to eliminate having to use the mouse to do so.  Then I discovered Cinnamon's ALT-TAB window switching.   Microsoft Windows users are no doubt laughing, knowing that they had this feature forever. I guess that's true, but I never used it, and probably not that many other Windows users do either.

The point is that Cinnamon supports efficient desktop navigation that efficiency-minded Linux users will want to use.  Here's window switching with Linux Mint Cinnamon with ALT-TAB.  No mouse required.

You can go for fancier window navigation with Cinnamon extensions like CoverFlow AltTab.  Here's a screenshot of that.

Don't forget, since Cinnamon is based on GNOME 2, all of the GNOME keyboard desktop shortcuts are also available.  Here's an excellent list of GNOME Keyboard Shortcuts at the LinuxMint.com Community site.

Author: "--" Tags: "Linux"
Comments Send by mail Print  Save  Delicious 
Date: Monday, 08 Apr 2013 16:20

I read several instructions on upgrading RubyGems in Linux and didn't have much success until discovering the Rubygems-Update Gem.  With Rubygems-Update keeping my RubyGems version current is no longer an issue.

Using one recommended upgrade approach

$ gem update —system

displayed the Debian "set the REALLY_GEM_UPDATE_SYSTEM environment variable" error message.

Fortunately it was then I discovered the Rubygems-Update Gem.

$ sudo gem install rubygems-update
$ sudo update_rubygems

Rubygems-update installed and RubyGems updated!

$ gem env

confirms we're up to speed with the latest RubyGems.

 

Big thanks to Sameera Gyan and his post Upgrading Ruby Gems on Ubuntu Linux. And of course, thank you to the authors of the RubyGems-Update Gem!

Author: "--" Tags: "Ruby"
Comments Send by mail Print  Save  Delicious 
Date: Friday, 05 Apr 2013 14:49

If you're like me you find yourself using cloud storage more and more.  Most cloud services like the two I use most often, Dropbox and Ubuntu One, tell us that our documents are secure and I believe them.  But I've been around long enough to know that bad stuff happens in the Cloud and that it's simply not prudent to trust any Cloud service with your most important data. 

This is where GnuPG comes in.  GNU Privacy Guard (GPG for short) gives you the confidence to store your confidential documents on any cloud service, using a key-based encryption and decryption system that is easy to implement.

You could use any number of approaches to protecting your cloud content.  Using LibreOffice's Document Password feature is one approach, for example. 

For most documents you want to store in the cloud that should be sufficient, but what if you simply can't take any chances?  That's when you might consider GPG encryption and decryption. 

Getting Started with GnuPG

GnuPG is installed with most Linux distributions, so there should be nothing you need to install.  The first thing you'll want to do is create a personal Key.  GPG key creation is well documented and found on many blogs and articles on the Internet so simply search for GnuPG Create Key and you're set. You will also see that there is nothing to it.

The Script

Now we'll want to create a bash script to encrypt and store our secure document in the cloud.  We also might want a script to retrieve and decrypt the document if we want to share it from multiple Linux machines.  So let's create a single script and use --encrypt or --decrypt parameters to specify the action we want.

We named the script gpgNotes.sh, so to run the script we go into the terminal and enter

$ gpgNotes.sh --encrypt

to encrypt and sign our document and copy it to the cloud, and

$ gpgNotes.sh --decrypt

to grab the file from the cloud, decrypt it and save it locally.

With GnuPG we can use the cloud with confidence!

Author: "--" Tags: "Linux"
Comments Send by mail Print  Save  Delicious 
Date: Thursday, 04 Apr 2013 21:47

Like most of us, my work is divided between a laptop and a PC and I use cloud services like Dropbox and Ubuntu One to share data between them.  Grsync and Rsync takes data sharing to the next level, giving me the ability to synchronize updates among multiple Linux machines.

If you come from a Windows background, think of Rsync as a Robocopy for Linux.  Rsync, like Robocopy, is an intelligent file backup command line tool copying only those files you specify.  Typically we're only copying the files that have been modified since the last time Robocopy was run resulting in a very efficient copy process.  Rsync has all of the capabilities of Robocopy with one big advantage, its Grsync graphical UI.  Here's a screenshot of Grsync.

For the Rubyists out there looking at the source and destination properties of the above example, yes, Git or some other version control system is the best way to keep project files in sync, but let's ignore that point for now.  Our purpose here is to demonstrate keeping files updated on multiple Linux machines.

Our example shows copying updated files from a machine to a cloud service.  To complete the update on another machine we'd reverse the process.  It should be noted that each task can be saved as what is called a "Session" in Grsync.  This is a configuration file you create once and can use with multiple machines. I keep my Grsync Session Config files on a cloud drive so I can load the configurations from any machine. 

You'll notice below how we can include additional properties for setting exclude and log files.

One of my favorite features of Grsync is the ability to perform dry runs as shown below.  This gives you a preview of what files will be copied and confirms the process will copy the files you were expecting it to copy

Not only are you presented with a list of files that will be copied but a command line statement is generated from your GUI settings.  You can use the command to learn more about rsync or use it in a bash script.

I hope I've demonstrated how darn handy Grsync and Rsync can be in keeping your files synchronized among multiple Linux machines.

Author: "--" Tags: "Linux"
Comments Send by mail Print  Save  Delicious 
Date: Thursday, 04 Apr 2013 16:33

According to Wikipedia, a Koan is a story, dialogue, question or statement used in Zen practice to provoke the "great doubt" and test a student's progress.  When referring to learning Ruby, the Koans Project is a valuable introduction and learning tool. 

The Neo Ruby  Koans project gives you hands-on experience with the main aspects of Ruby, covering blocks, classes, constants, hashes, arrays and much more.  It takes you through a series of subject-specific project test scripts where you provide the answers as in the following example.

array =  [1, 2, 3]
new_array = array.collect { |item| item + 10 }
asset_equal __ , new_array

Your task is to fill in the "__" test assertion value.

Taking the Test

When you launch the project with

$ rake

the test will be evaluated displaying the success or failure of the test.  Here's what that looks like in Sublime Text and a terminal session in Linux Mint.

Koans also requires you to write a few simple classes to support completed Test Assert definitions, like this one for determining triangle types.

Here's a sample Koans Test Assertion statement which the above Ruby definition needs to satisfy.

assert_equal   :scalene , triangle(3, 4, 5)

How long it takes to complete the Neo Ruby Koans test obviously depends on your familiarity with Ruby.  If you're starting out with Ruby the Koans Test Project is worth the investment, whether it takes you days or even weeks to find, um, enlightenment.

Author: "--" Tags: "Ruby"
Comments Send by mail Print  Save  Delicious 
Next page
» You can also retrieve older items : Read
» © All content and copyrights belong to their respective authors.«
» © FeedShow - Online RSS Feeds Reader