Halaman

Minggu, 21 November 2010

[shared] rails custom ajax helper for jquery

requirements:
- jrails plugin (https://github.com/aaronchi/jrails)
- working jquery.gritter or other js notification (http://boedesign.com/blog/2009/07/11/growl-for-jquery-gritter/)
- my jquery.extended_helper (http://code.google.com/p/jquery-extendedhelper)

installation:
- add these code in application_helper.rb
# Adding additional options for ajax function
# You can use thisElement to manipulate element that using the function (link/button/form)
def custom_remote_function_options options
  options[:before] ||= ""
  options[:loading] ||= ""
  options[:complete] ||= ""
  options[:success] ||= ""
  options[:before] += "; var thisElement=this"
  options[:failure] ||= "; eval(request.responseText)"

  unless options[:loading_text].blank?
    options[:loading] += "; thisElement.notif = #{notification_loading(options[:loading_text])}"
    options[:complete] += "; #{notification_remove "thisElement.notif"}"
  end
  options
end

# Override rails remote_function using additional options
def custom_remote_function options
  remote_function(custom_remote_function_options(options)).html_safe
end

# Override rails link_to_remote function using additional options
# Disabling the link when ajax loading in progress to avoid double request
def custom_link_to_remote name, options={}, html_options=nil
  options = custom_remote_function_options options
  options[:loading] += "; $(thisElement).setLink(false)"
  options[:complete] += "; $(thisElement).setLink(true)"
  link_to_remote name, options, html_options
end

# Override rails button_to_remote function using additional options
# Disabling the button when ajax loading in progress to avoid double request
def custom_button_to_remote name, options={}, html_options=nil
  options = custom_remote_function_options options
  options[:loading] += "; $(thisElement).setInput(false)"
  options[:complete] += "; $(thisElement).setInput(true)"
  button_to_remote name, options, html_options
end

# Adding additional options for ajax form
# Add :unchange_default => true to prevent successful request changing default form fields value
# Add :disable_link => true to disable all link inside form when loading in progress
def custom_remote_form_options options
  options = custom_remote_function_options options
  options[:loading] += "; $(':input', thisElement).setInput(false);"
  options[:complete] += "; $(':input', thisElement).setInput(true);"
  unless options[:unchange_default]
    options[:success] +=  "; $(':input', thisElement).setDefault();"
  end
  if options[:disable_link]
    options[:loading] += "; $('a', thisElement).setLink(false);"
    options[:complete] += "; $('a', thisElement).setLink(true);"
  end
  options
end

# Override rails remote_form_for using additional options
def custom_remote_form_for record_or_name_or_array, *args, &proc
  args.push custom_remote_form_options(args.extract_options!)
  remote_form_for record_or_name_or_array, *args, &proc
end
alias_method :custom_form_remote_for, :custom_remote_form_for

# Override rails form_remote_tag using additional options
def custom_form_remote_tag options={}, &block
  form_remote_tag custom_remote_form_options(options), &block
end
alias_method :custom_remote_form_tag, :custom_form_remote_tag

def custom_button_to_remote name, value, options = {}
  button_to_remote name, value, custom_remote_form_options(options)
end

# Override rails submit_to_remote using additional options
def custom_submit_to_remote(name, value, options = {})
  submit_to_remote(name, value, custom_remote_form_options(options))
end

def notification_info text, no_escape=false
  text.gsub!(/\n/, '
')
  text = escape_javascript(text) unless no_escape
  "notificationInfo('#{text}')"
end

def notification_loading text, no_escape=false
  text.gsub!(/\n/, '
')
  text = escape_javascript(text) unless no_escape
  "notificationLoading('#{text}')"
end

def notification_error text, no_escape=false
  text.gsub!(/\n/, '
')
  text = escape_javascript(text) unless no_escape
  "notificationError('#{text}')"
end

def notification_remove notification
  "notificationRemove(#{notification})"
end

- add notification code in application.js (sample using jquery.gritter)
function notificationInfo(text){
  return $.gritter.add({text: text.replace(/\n/g, '
')});
}

function notificationError(text){
  return $.gritter.add({text: '' + text.replace(/\n/g, '
') + '',time: 6000});
}

function notificationLoading(text){
  return $.gritter.add({text: text.replace(/\n/g, '
'), image: '/images/gritter-loading.gif', sticky:true})
}

function notificationRemove(notification){
  $.gritter.remove(notification);
}

rails http status code and symbol

Status CodeStatus MessageSymbol
1xx Informational
100Continue:continue
101Switching Protocols:switching_protocols
102Processing:processing
 
2xx Success
200OK:ok
201Created:created
202Accepted:accepted
203Non-Authoritative Information:non_authoritative_information
204No Content:no_content
205Reset Content:reset_content
206Partial Content:partial_content
207Multi-Status:multi_status
226IM Used:im_used
 
3xx Redirection
300Multiple Choices:multiple_choices
301Moved Permanently:moved_permanently
302Found:found
303See Other:see_other
304Not Modified:not_modified
305Use Proxy:use_proxy
307Temporary Redirect:temporary_redirect
 
4xx Client Error
400Bad Request:bad_request
401Unauthorized:unauthorized
402Payment Required:payment_required
403Forbidden:forbidden
404Not Found:not_found
405Method Not Allowed:method_not_allowed
406Not Acceptable:not_acceptable
407Proxy Authentication Required:proxy_authentication_required
408Request Timeout:request_timeout
409Conflict:conflict
410Gone:gone
411Length Required:length_required
412Precondition Failed:precondition_failed
413Request Entity Too Large:request_entity_too_large
414Request-URI Too Long:request_uri_too_long
415Unsupported Media Type:unsupported_media_type
416Requested Range Not Satisfiable:requested_range_not_satisfiable
417Expectation Failed:expectation_failed
422Unprocessable Entity:unprocessable_entity
423Locked:locked
424Failed Dependency:failed_dependency
426Upgrade Required:upgrade_required
 
5xx Server Error
500Internal Server Error:internal_server_error
501Not Implemented:not_implemented
502Bad Gateway:bad_gateway
503Service Unavailable:service_unavailable
504Gateway Timeout:gateway_timeout
505HTTP Version Not Supported:http_version_not_supported
507Insufficient Storage:insufficient_storage
510Not Extended:not_extended

source: http://www.codyfauser.com/2008/7/4/rails-http-status-code-to-symbol-mapping

Rabu, 17 November 2010

[shared] array/hash support for system_settings

https://github.com/realityforge/rails-system-settings

# system_settings/lib/system_setting.rb

class SystemSetting < ActiveRecord::Base
@@data = {}

validates_length_of :name, :in => 1..255
validates_uniqueness_of :name

serialize :value

def self.[](name)
name = name.to_s unless name.is_a? String
return @@data[name] unless @@data[name].nil?
p = SystemSetting.find_by_name(name)
@@data[name] = p ? p.value.freeze : nil
end

def self.[]=(name, value)
name = name.to_s unless name.is_a? String
p = SystemSetting.find_or_initialize_by_name(name)
@@data[name] = p.value = value
p.save!
p.value.freeze
end
end

[shared] Unsigned int support for migration

currently rails only allow signed int for migration, but for best practice it's better to use unsigned int for some cases

you can force migration to unsigned int by doing something like this

t.column :unsigned_value, "integer unsigned"


but that kinda ugly to see.
luckily rob anderton (thewebfellas.com) already created monkey patch to add unsigned support: http://thewebfellas.com/assets/2008/9/30/active_record_unsigned.rb

the patch will add :unsigned option in migration so you can do something like this:

t.integer :unsigned_value, :unsigned => true


furthermore the patch will make default table id and foreign key to unsigned int(11), but make sure to use t.references to create foreign key or simply use :unsigned => true

important things:


- for existing project this patch might break table relation because it will create unsigned int foreign key but the primary key might be signed int from old migration
- some plugin like role_requirement will generate migration that using t.integer for foreign key instead of t.references, you need to change this manually
- the patch will only change mysql adapter, so it will not work for other adapter

[shared] Rails migration integer limit

:limit Numeric Type Column Size Signed Max value Unsigned Max value
1 TINYINT(4) 1 byte 127 255
2 SMALLINT(6) 2 bytes 32767 65535
3 MEDIUMINT(9) 3 bytes 8388607 16777215
4 and others INT(11) 4 bytes 2147483647 4294967295
5..8 BIGINT(20) 8 bytes 9223372036854775807 18446744073709551615

Minggu, 14 November 2010

[shared] rails user role system

https://github.com/timcharper/role_requirement

installation:
- ruby script/generate roles Role User

installation will do:

  • Generates habtm table, creates role.rb with the habtm declaration. Adds declaration in user.rb (scans the code for "class User < ActiveRecord::Base", and puts the new code right after it.



  • Creates an admin user in users.yml, with a role named admin in roles.yml, including a fixture to demonstrate how to relate roles to users in roles_users.yml



  • Modify the user.rb (or corresponding user model) file, add the instance method has_role?



  • Generates RoleRequirementSystem against for the corresponding user model.



  • Generates a migration to make the necessary database changes



  • Scans ApplicationController, inserts the lines "include AuthenticatedSystem", and "include RoleRequirementSystem", if not already included.



  • Scans test_helper.rb and adds "includes RoleRequirementTestHelpers", if not already included.




Usage:
- add require_role "role_name" in controller, similar to before_filter

[shared] rails exception logger

https://github.com/defunkt/exception_logger

installation:
- ruby script/generate exception_migration
- rake db:migrate
- in application_controller.rb add
include ExceptionLoggable
rescue_from Exception, :with => :exception_handler

private

def exception_handler exception
log_exception exception
render "/500.html"
end


the default controller and view using prototype.js instead of jquery so i created my own controller view under admin namespace. the database pretty simple and similar to rails exception notification

for rails 3:
https://github.com/QuBiT/exception_logger

Rabu, 10 November 2010

kaspersky conflicting with tortoise svn

kaspersky, settings, exclusions, add:
- rules for the project folder
- trusted application for:
- - ..\system32\searchprotocolhost.exe
- - ..\system32\searchfilterhost.exe
- - ..\tortoisesvn\bin\tsvncache.exe
- - ..\tortoisesvn\bin\tortoiseproc.exe
- - ..\tortoisesvn\bin\tortoisemerge.exe

other possible cause:
win7 bug prior sp1: http://support.microsoft.com/kb/982927/en-us

Kamis, 04 November 2010

Mysql::Error: query: not connected

MySQL 5.1 client library doesn't play well with Rails

download:
http://instantrails.rubyforge.org/svn/trunk/InstantRails-win/InstantRails/mysql/bin/libmySQL.dll

source:
http://forums.aptana.com/viewtopic.php?f=20&t=7563&p=27407&hilit=libmysql.dll#p27407