Some Possibly less know ActiveRecord configuration options

Posted by Randy on March 19, 2009

I am going to list from the guides.rubyonrails.com site, some possibly less know, but useful configuration options for ruby on rails. I didn’t know these existed until I had to figure out an elegant way to prefix tables with something, and I didn’t want to just type it into the migrations and models. Here is how you set the variables:

In your config/environments/development.rb (or production.rb, or whatever.rb) do the following:

config.active_record.table_name_prefix = "whatever_"

You can also select any of the following options instead of table_name_prefix to configure active record globally. Here is the list:

ActiveRecord::Base includes a variety of configuration options:

* logger accepts a logger conforming to the interface of Log4r or the default Ruby 1.8.x Logger class, which is then passed on to any new database connections made. You can retrieve this logger by calling logger on either an ActiveRecord model class or an ActiveRecord model instance. Set to nil to disable logging.

* primary_key_prefix_type lets you adjust the naming for primary key columns. By default, Rails assumes that primary key columns are named id (and this configuration option doesn’t need to be set.) There are two other choices:
o :table_name would make the primary key for the Customer class customerid
o :table_name_with_underscore would make the primary key for the Customer class customer_id

* table_name_prefix lets you set a global string to be prepended to table names. If you set this to northwest_, then the Customer class will look for northwest_customers as its table. The default is an empty string.

* table_name_suffix lets you set a global string to be appended to table names. If you set this to _northwest, then the Customer class will look for customers_northwest as its table. The default is an empty string.

* pluralize_table_names specifies whether Rails will look for singular or plural table names in the database. If set to true (the default), then the Customer class will use the customers table. If set to false, then the Customers class will use the customer table.

* colorize_logging (true by default) specifies whether or not to use ANSI color codes when logging information from ActiveRecord.

* default_timezone determines whether to use Time.local (if set to :local) or Time.utc (if set to :utc) when pulling dates and times from the database. The default is :local.

* schema_format controls the format for dumping the database schema to a file. The options are :ruby (the default) for a database-independent version that depends on migrations, or :sql for a set of (potentially database-dependent) SQL statements.

* timestamped_migrations controls whether migrations are numbered with serial integers or with timestamps. The default is true, to use timestamps, which are preferred if there are multiple developers working on the same application.

* lock_optimistically controls whether ActiveRecord will use optimistic locking. By default this is true.

Paperclip and getting the original file path before its uploaded

Posted by Randy on March 17, 2009

Back to some rails stuff. Here is a little tip that helped me out with reading in the file that was being uploaded before I saved the record. I was doing this because I wanted to validate the data in the file before I save the record. Here is what I did:

class SomeModel < ActiveRecord::Base
  has_attachment :some_file
 
  def validate
    file = self.some_file.to_file(:original)
    data = File.read(file)
    # Do some validation on data
    errors.add_to_base "File format invalid" if data.nil?
  end
end

Facebook and CPA.. will it work? 1

Posted by Randy on March 16, 2009

Hey all. I’m still having a try at the affiliate marketing stuff. I just signed up with Facebook Advertising to try my hand at that.
I have decided I was going to try and use the targeting in Facebook to help show my ad to ONLY those I want interested in the offer. The setup was pretty easy, and once I figured out what Facebook wanted for criteria, it was easy to get them approved. Normally I go with the CPC model, but with Facebook, I am trying the CPM model. So far it seems to be rather cost effective. So far I haven’t made a conversion yet, but it is still the beginning.
I will keep you tuned.

Venturing into CPA, Adwords, and Affiliate Marketing 2

Posted by Randy on March 14, 2009

Taking a small change of pace from the rails stuff, I have looked into doing some affiliate marketing. I have been reading a lot on the WarriorForum and signed up with NeverBlueAds.
I decided I was going to pick an offer, create a landing page, and drive traffic to it using Adwords. I picked an offer that was a low paying one as I figured I wouldn’t have to spend too much in Adwords while I tested the waters.
Once I picked the offer, I created a landing page trying to push potential “customers” to the affiliate link. Next I went into Adwords and created a new ad, using only the Content network. I decided to do this because I could control what pages and what keywords I wanted the ads to show for. I picked a bunch of sites that were relevant to the offer.
I ended up making about $24, but spending about $50 in adwords. Not too bad for my first attempt. I will continue to refine my processes and try to build a winner!

How to merge strings just like ActiveRecord conditions do 1

Posted by Randy on March 13, 2009

While you can achieve the same functionality using sprintf, this may provide a cleaner approach and one that you are more familiar with. This will allow you to build a string the same way you can use ActiveRecord and the :conditions option.
Basically how this works is by overriding the Array class and adding a method to merge the string and values together into unified string! Enough talk, lets see some code:

class Array
  def merge
    statement, *values = self
    expected = statement.count("?")
    provided = values.size
    raise "wrong number of bind variables (#{provided} for #{expected}) in: #{statement}" unless expected.eql?(provided)
    bound = values.dup
    statement.gsub("?") { bound.shift }
  end
end

As you can see, if you do not provide the right number of values for the statement, it will raise and error. Here is how you would use it:

puts ['Hello ?, how are you', 'John'].merge
#=> Hello John, how are you

Likewise, you can use variables to hold values:

message = "Hello ?, how are you"
name = 'John'
puts [message, name].merge
#=> Hello John, how are you

This will also work with multiple values:

puts ['Hello ?, ? and ?, how are you', 'John', 'Joe', 'Jim'].merge
#=> Hello John, Joe, and Jim, how are you

The only downside to this currently is that you cannot use a ? in the string you are merging, as it will think its a binding character.

NoMethodError on nil.each?

Posted by Randy on March 12, 2009

Have you ever have to iterate over an array from say the params hash? You probably have added some code to make sure that data exists in the hash element first before doing the loop. This is a cool little trick to help condense some code. Normally I would write this:

if params[:accounts] and params[:accounts].size > 0
  params[:accounts].each do |account|
    # Do something with account here
  end
end

As you can see, kind of ugly. Here is the change:

(params[:accounts] || []).each do |account|
  # Do something with account
end

AHH!!! Must nicer!

Moving files in Rails using String 1

Posted by Randy on March 05, 2009

Since ruby allow for really easy overriding of objects and classes, I decided to make it easier and cleaner to move my files. Here is how you currently do it:

FileUtils.move("/path/to/file", "/path/to/new/file")

I know this isn’t a huge deal, but I would like to clean it up a little bit. I used an initializer (RAILS_ROOT/config/initializers/core_extensions.rb) to override the String class as such:

class String
   def move(to = nil)
     if to
       if File.exist?(self)
         FileUtils.move(self, to)
       end
     end
   end
end

This allows me to do the following to move files:

"/path/to/file".move("/path/to/new/file")

I though it was pretty cool!