Showing posts with label rails. Show all posts
Showing posts with label rails. Show all posts

Thursday, July 15, 2010

rails - Forcing a certain encoding type for the page

response.headers["Content-Type"] = "text/html; charset=shift_jis"

rails - using truncate from a the lib dir ie a module

Here is how to get the helpers into the libs area, Sometimes the helpers use/set data on the controller etc so this doesn't work.

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='

Problem:
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

I just noticed that "DEFAULT_RAILS_LOGGER" is not working in libs on some of the newer rails versions.. The new alternative is "Rails.logger" it seems to work perfectly fine.

Saturday, July 3, 2010

Rails DateTime converting into your time zone

Quick and dirty way to get a time into your locale

DateTime.parse(some_other_time_string).in_time_zone(::Time.zone)

Rails - 422 error code

The Rail 422 error code is a bit of an odd ball.


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

Here is a quick hacky way to make an array of check boxes for a rails form.

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

Rails doesn't clean up it session. This will wipe the active record sessions in the newer version of rails without wasting as much memory as a destroy all.

rows = ActiveRecord::SessionStore::Session.delete_all ["updated_at < ?", time]

Monday, April 26, 2010

Rails non-RESTful form_for

if you dont use the "map.resources" line in routes you are not making a restful app that means that the *_path *_url helper break too get around it you need to spec the url in form_for etc

<% form_for( @object, :url => {:action => 'update', :id => @object } :name => 'form') do |form| %> 

Friday, April 23, 2010

Rails Cookie and ActiveRecord Sessions

Rails by default uses an encrypted cookie store. Problem is that this store is limited to 4k if you need the space you should switch to something else

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_store
Then to create the sessions table execute;

rake db:sessions:create
rake db:migrate

Wednesday, April 14, 2010

Executing sql from rails console

All ways useful...

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

Rails(2.3.5) date parsing is busted IMO.

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

Again with Tarantula - here a way to test all pages for missing translations while you are spidering.

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

Tarantula and excellent rails fuzzy spider. But its doc sucks..

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.

When an active record has 2 belongs_to lines pointing to the same table the searching fails... notice the ordering of the 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

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

2 belongs_to pointing to the same table and searching fails...

(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..

maybe not the best.. but im a semicon guy and my rails stuff is for play so sue me

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