response.headers["Content-Type"] = "text/html; charset=shift_jis"
Thursday, July 15, 2010
rails - Forcing a certain encoding type for the page
rails - using truncate from a the lib dir ie a module
module MyModule include ActionView::Helpers::TextHelper module_function :truncate end
Here is how to get it on the console
helper.truncate(string, :length => length)
Monday, July 5, 2010
rails testing - undefined method `request='
test_some_functional_test_case(SomeFunctionalControllerTest): NoMethodError: undefined method `request=' for #<SomeMispeltFunctionalController:0x7f5b55bd0a58>
Solution:
Basically it means you haven't required the controllers file. Or you have a typo in the name that is instantiating the a non controller for the @controller variable in the test.
rails - DEFAULT_RAILS_LOGGER not working in libs
Saturday, July 3, 2010
Rails DateTime converting into your time zone
DateTime.parse(some_other_time_string).in_time_zone(::Time.zone)
Rails - 422 error code
Most likely cause of this is the CSRF is firing and killing whatever is posting to your site from outside in my case its PAYPAL posting an IPN request to a site im working on.
To fix it add this line of code to the controller
If entire controller can be posted to from out side then this is ok
skip_before_filter :verify_authenticity_token
If you need to open access to a single page then try this:
protect_from_forgery :execpt => :pages_that_are_posted_to_from_out_side
Wednesday, June 16, 2010
Rails - array of checkboxes
Warning: This version of the code hasnt been tested. It most likely needs some debug.
class ModelB < ActiveRecord::Baseclass
attr_accessor :name
attr_accessor :value
end
class ModelA < ActiveRecord::Baseclass
has_many :model_bs
end
<% form_for( @model_a,
:url => {:action => 'new' },
:html => {:method => :post } ) do |form| %>
<ul class="checkbox_array">
<% ModelB.find(:all, :order => 'position asc').each do |item| %>
<li>
<%= check_box_tag 'model_a[model_b_ids][]', item.id,
form.object.model_bs.include?(item),
{ :id => "model_a_model_b_ids_#{item.id}" } %>
<label for="<%= "model_a_model_b_ids_#{item.id}" %>"><%= h(item.name) %></label>
</li>
<% end %>
</ul>
<%= submit_tag t('New') %>
<% end %>
Tuesday, June 15, 2010
Ruby get all global constants
Object.constants.sort.uniq
Object.const_get("RUBY_VERSION")
Object can of course be replaced with any class to see its local constants
Monday, May 17, 2010
Rails - wiping sessions from the ActiveRecordSession store
rows = ActiveRecord::SessionStore::Session.delete_all ["updated_at < ?", time]
Monday, April 26, 2010
Rails non-RESTful form_for
<% form_for( @object, :url => {:action => 'update', :id => @object } :name => 'form') do |form| %>
Friday, April 23, 2010
Rails Cookie and ActiveRecord Sessions
Here is how to switch to an active record store:
add the following line to config/environment.rb
config.action_controller.session_store = :active_record_storeThen to create the sessions table execute;
rake db:sessions:create rake db:migrate
Wednesday, April 14, 2010
Executing sql from rails console
ActiveRecord::Base.connection.execute("SELECT * FROM users")
ActiveRecord::Base.connection.execute("select * from customers").fetch_row
results = ActiveRecord::Base.connection.execute("select * from customers")
while row = results.fetch_row do
# process row here
end
Monday, April 12, 2010
Rails built in Date parsing fixes
Try this: Place a date_select that allows blanks into a form and then enter the date 2010, "", 31 -- IE no month and the day 31 and submit the form. The result is a crash from a MultiparameterAssignmentErrors exception.
I dont care why it was does it.. to me its wrong here is the fix;
module ActiveRecord
class Base
def assign_multiparameter_attributes(pairs)
begin
execute_callstack_for_multiparameter_attributes(
extract_callstack_for_multiparameter_attributes(pairs))
rescue MultiparameterAssignmentErrors => e
e.errors.each { |err|
self.errors.add(err.attribute)
}
end
end
end
end
Friday, April 9, 2010
Rails - Tarantula spider testing - finding broken I18n translations
class Relevance::Tarantula::MissingI18nTranslationHtmlHandler
include Relevance::Tarantula
def handle(result)
begin
response = result.response
return unless response.html?
if /translation missing/.match(response.body)
error_result = result.dup
error_result.success = false
error_result.description = "Broken Translation"
error_result
end
rescue
end
return nil
end
end
class TarantulaTest < ActionController::IntegrationTest
fixtures :all
require 'ruby-debug'
def test_tarantula
login_all_users
t = tarantula_crawler(self)
t.handlers << Relevance::Tarantula::MissingI18nTranslationHtmlHandler.new
t.crawl "/"
end
def login_all_users
end
end
RAILS - tarantula
The docs advise to unpack the gem into the vendors dir... and then add this the rake file
load File.join(RAILS_ROOT, Dir["vendor/gems/tarantula-*/tasks/*.rake"])
Dont unpack it. Total waste of space and time... load it from the gem install location it like this
tarantula_path = Gem::required_location("tarantula", "")
if tarantula_path
Dir[ File.join(tarantula_path, "..","tasks","*.rake") ].each {
|rakefile| load rakefile
}
end
ordering of includes.
(rdb:1) Customer.find(:all, :conditions => ["#{Address.table_name}.name_given = 'kdFJf6J6Mdx'"], :include => [:address, :shipping_address] )
[]
(rdb:1) Customer.find(:all, :conditions => ["#{Address.table_name}.name_given = 'kdFJf6J6Mdx'"], :include => [:shipping_address, :address] )
[#<Customer id: 81, ...SNIP... >]
Rails/Ruby backtraces
begin
asd
rescue => e
logger.info "BACKTRACED HERE"
bt = e.backtrace.delete_if{ |l| !(/private_stuff/ =~ l) }
logger.info YAML::dump(bt)
end
Monday, August 10, 2009
rails "bugs" 2 belongs to pointing to the same table
(rdb:1) Customer.find(:all, :conditions => ["#{Address.table_name}.name_given = 'kdFJf6J6Mdx'"], :include => [:address, :shipping_address] )
[]
(rdb:1) Customer.find(:all, :conditions => ["#{Address.table_name}.name_given = 'kdFJf6J6Mdx'"], :include => [:shipping_address, :address] )
[#]
decide for your self...
1) The problem can be fixed by using the :joins option. to search both fields
2) The problem can be exploted to expand the full set of child records linked via has_many with eager loading while searching for a field contained in the children to locate the the parents.. Generally searches from the parent into child will limit the children to only the matching ones...(which is a problem 90% of the time)
Thursday, August 6, 2009
ruby on rails - dumping the stack -hack..
begin
asd
rescue => e
logger.info ""
logger.info "skip_full_validation #{ret} - #{self.shipping_flag}"
bt = e.backtrace.delete_if{ |l| !(/meat-guy/ =~ l) }
logger.info YAML::dump(bt)
end