Ruby
Make Mysql throw an exception for Rails app to handle
daniel Mon, 10/30/2017 - 1:54pm
If you want to test what your rails app does when it hits a rails exception, one thing you can do is the following. Change the query slightly:
myDomainObj.where(my_param: "myval")
to:
myDomainObj.execute("SIGNAL SQLSTATE 'ERROR'")
Forking Processes In Ruby On Rails
daniel Thu, 02/24/2011 - 1:11pm
Inspired By this post on makandra.com.
This incarnation was not tested, so there could be a typo. I pulled it out of some other code, and didn't want to reveal my super secret business logic...
- Read more about Forking Processes In Ruby On Rails
- Log in to post comments
Run a Single Rails3 Test Class
daniel Mon, 02/21/2011 - 3:31pm
At the command line (for a functional test):
rake test:functionals TEST=test/functional/my_app_controller_test.rb
or unit test
rake test:units TEST=test/unit/my_app_test.rb
Where test/functional/my_app_controller_test.rb is a relative or full path to the test class you want to run.
Specifying "test:functionals" or "test:units" is just to get the tests to run once. If you just specify "test", it will run the tests twice due to some rails bug.
From Flavio Castelli's site
- Read more about Run a Single Rails3 Test Class
- Log in to post comments
Ruby Notes
daniel Tue, 02/15/2011 - 11:11am
Ruby Notes/Quotes from Ruby Pick Axe Book:
VARIABLES:
The first characters of a name indicate how the name is used.
• Local variables, method parameters, and method names should all start with a lowercase letter or with an underscore.
• Global variables are prefixed with a dollar sign ($),
• instance variables begin with an “at” sign (@).
• Class variables start with two “at” signs (@@).2 Finally,
• class names, module names, and constants must start with an uppercase letter. Samples of different names are given in Table 2.1 on the next page. (pg 41
• Constants are referenced by Class/Modulename::ConstantName
Following this initial character, a name can be any combination of letters, digits, and under-scores (with the proviso that the character following an @ sign may not be a digit).
However, by convention, multiword instance variables are written with underscores between the words, and multiword class names are written in MixedCase (with each word capitalized).
Method names may end with the characters ?, !, and =.
Pick Axe: pg55
METHODS:
def my_method (arg1, arg2=false)
..method with args, some default args..
end
def my_method_2
..no args..
end
Convention:
If returning a boolean, end name with ?
If method is dangerous or modifies receiver, end name with !
CLOSURES:
Can only be created as a parameter to a method...
To execute a Closure given as a parameter in your method, use the special variable name yield
def my_method
yield my_closure_pararm
end
To find out if a closure was passed to your method, use the method:
block_given?
which returns a boolean
Can be explicitly named as an object in your method def...
def my_method($closure_var)
closure_var.call
end
Can assign directly to a var using the method:
closure_var = lambda do | my_var |
puts my_var
end
closure_var.call "Bark"
Can also do
closure_var = -> my_var { puts my_var }
INHERITANCE:
class Animal
end
class Dog < Animal
end
CLASSES:
calling parent class functionality: super(params)
MODULES:
Similar to classes, but no instance methods:
module Actions
def Actions.walk()
end
end
MIXINS:
Allow you to get methods from a module in a class
just use:
include ModuleName
in the class.
Standard Types:
Numbers: Fixnum, Bignum, Float, Integer, Numeric, Rational, Complex
Some Loops:
3.times {}
3.upto(5) {}
3.downto(1) {}
3.step(5,1) {}
- Read more about Ruby Notes
- Log in to post comments
Deploying a Rails3 app to a subdirectory with apache2 and passenger
daniel Sun, 01/30/2011 - 2:09pm
Create symlink to your public directory in your app:
ln -s /var/www-rails/passhasher/current/public /var/www/passhasher
Create configuration in your existing virtualhost directive in apache:
<Directory /var/www/passhasher/>
PassengerEnabled on
PassengerAppRoot /var/www-rails/passhasher/current
Options -MultiViews +FollowSymLinks
</Directory>
I've cached the applicable information from http://www.site5.com/blog/programming/how-to-enable-rails-3-0-on-site5/20101007/ below:
Deploying to a Sub-Directory
Deploying to a sub-directory is fairly simple in Rails 3. You do not need to make any different changes to your .htaccess file, but you do need to adjust your routing and environment slightly.
Let’s say you are deploying to ‘http://yourdomain.com/rails3/’ in this example. You would need to add the following to your routes.rb file:
scope "/rails3"
# all of your routes go here
end
The “scope” part needs to be contained in the “Rails3test::Application.routes.draw do” part of your routes file. Here is what mine looks like:
Rails3test::Application.routes.draw do
scope "/rails3" do
resources :users
root :to => "users#index"
end
end
View: http://gist.github.com/615194
Making this adjustment will probably cause your static elements (javascript, stylesheets, image files) to stop working. To fix this problem, open up your environment.rb file (~/rails3test/config/environment.rb):
vi ~/rails3test/config/environment.rb
Add the following line to the top of the file:
ENV['RAILS_RELATIVE_URL_ROOT'] = "/rails3"
View: http://gist.github.com/615198
That should fix the issues with your stylesheets and javascript files. You will probably need to restart your application (touch ~/rails3test/tmp/restart.txt), so Passenger can pickup the changes.
Rails3, protect your database password
daniel Fri, 01/28/2011 - 10:39pm
A very good article at: http://www.simonecarletti.com/blog/2009/06/capistrano-and-database-yml/
A rough cut at making a gem with the above: https://github.com/amfranz/capistrano_database_yml
Steps:
Add gem to Gemfile (Follow instructions in gemfile readme)
Commit changes
cap deploy:update
cap deploy:setup
Edit deployed database config file in shared/config/database.yml on the server
On server, can load the schema with:
rake RAILS_ENV=production db:schema:load
If it fails, tells you something above didn't quite work as intended.
- Read more about Rails3, protect your database password
- Log in to post comments
Using Ruby 1.9 to Post to Wordpress using XML-RPC -- Importing an archived site to Wordpress
daniel Thu, 01/13/2011 - 2:44pm
Just putting this script out there as an example of code that reads the database of an archived forum (written in php) and posts to Wordpress using Ruby.
The communication from Ruby to Wordpress happens with the xml-rpc api.
You will need to turn on xml-rpc access in Wordpress for it to work.
Error Handling according to Requested Format in Rails 3
daniel Thu, 01/13/2011 - 12:56pm
This code is for Rails3, and will allow you to display a json object with the proper http status code if your api throws an exception, or forward to a page and display a flash message for your users.
In application_controller.rb add/modify the following code
rescue_from MyCriticalError, :with => :render_500
#
def render_500 error
#maybe do some logging here - or notify someone directly
render_error_according_to_format error, nil, nil, 500
end
#
# Render the error message according to the format of the request
# @param error The Error to render
# @param page_to_display The html path to forward to if that is the format
# @param text_error_message The text_error_message will override the message in the error object
# @param status_to_return The http status to return with the page
def render_error_according_to_format error, page_to_display, text_error_message, status_to_return
error_message = (text_error_message ? text_error_message : error.message)
page_to_display = page_to_display ? page_to_display : home_page_url
#
error_hash = {:type => error.class.name, :message => error_message }
#
respond_to do |format|
format.html { redirect_to page_to_display, :alert => error_message }
format.json { render :json => {error => error_hash}, :status => status_to_return }
end
end
Useful Links:
Rails Mime Types
Rails Http Status Codes - Provided through Rack
Postgres with Rails3
daniel Thu, 01/06/2011 - 2:19pm
Got the following error after following a slightly out of date post on using Postgres with Rails3:
Please install the postgres adapter: `gem install activerecord-postgres-adapter` (no such file to load -- active_record/connection_adapters/postgres_adapter) (RuntimeError)
I was using an incorrectly spelled adapter. It should be:
development:
adapter: postgresql
host: localhost
port: 5432
username: myappUser
password: myappPass
database: myappDbName_development
schema_search_path: public
encoding: utf8
template: template0
That in conjunction with this in your Gemfile:
gem 'pg'
Should have you connected.
Note: If you want to use postgres for the tests, you'll need to allow the role to create database objects. Something like:
CREATE ROLE myappuser LOGIN
ENCRYPTED PASSWORD 'encryptedpasswordhere'
NOSUPERUSER INHERIT CREATEDB NOCREATEROLE;
- Read more about Postgres with Rails3
- Log in to post comments
Syslog with Rails3 - The Bare Minimum
daniel Thu, 01/06/2011 - 9:29am
Some background on Syslog
There is already a comment in your config/environments/production.rb file:
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
uncomment and add an app name like:
# Use a different logger for distributed setups
config.logger = SyslogLogger.new 'myapp-prod'
Finally at the top of the file, add:
require 'syslog_logger'
Add this to your Gemfile:
gem 'SyslogLogger'
- Read more about Syslog with Rails3 - The Bare Minimum
- Log in to post comments
