Showing posts with label ActiveRecord. Show all posts
Showing posts with label ActiveRecord. Show all posts

Wednesday, March 18, 2015

How to Validate Regular Expressions in Ruby on Rails Models

ActiveRecord has many awesome validators for common things like presence, numericality, etc. Unfortunately, it is missing one common format - regex, or regular expressions. These are normally saved as string fields and, if not validated, can lead to page errors when your app tries to use a field that contains an invalid regular expression. This is especially the case if you allow the user to input a regular expression. With the addition of one small validation class, you will be able to prevent these sorts of bugs with your models.

The above code adds a validator called RegularExpressionValidator to app/validators/regular_expression_validator.rb. It then adds the validation to the Bear model on the field my_regex_field. With this, if you try and create a Bear with an invalid regular expression, an error will be thrown and the save will not complete.

Friday, January 16, 2015

Rake Database Tasks Outside Rails

My first content post is, ironically, not directly about Rails. It is about using a very common Rails feature - rake database tasks - in a Ruby project that utilizes ActiveRecord but not Rails.

By default, tasks like rake db:migrate are available in Rails but not in a Ruby project that includes ActiveRecord. Fortunately, with a couple of lines added to your Rakefile this issue can be fixed.
 // Rakefile
 DatabaseTasks.env = ENV['YOUR_ENV_VAR'] || 'development'  
 DatabaseTasks.db_dir = 'db'  
 DatabaseTasks.database_configuration = YAML.load_file('config/database.yml')  
 DatabaseTasks.migrations_paths = "#{DatabaseTasks.db_dir}/migrate"  
 task :environment do  
  ActiveRecord::Base.configurations = DatabaseTasks.database_configuration  
  ActiveRecord::Base.establish_connection DatabaseTasks.env.to_sym  
 end  
 load 'active_record/railties/databases.rake'  
And voila. Now, you can use create, migrate, and all of the other rake db tasks you're used to in a Rails project.