$('.serchStockInput').keypress(function (e) {
if(e.keyCode == 13) {
track();
return false;
}
});
2008年10月31日 星期五
2008年10月30日 星期四
composed_of,model,data object
http://hideto.javaeye.com/blog/77459
http://rorataspire.wordpress.com/2008/07/10/rails-composed_of/
http://api.rubyonrails.org/classes/ActiveRecord/Aggregations/ClassMethods.html#M001663
http://opensoul.org/2006/11/16/making-code-composed_of-code-more-useful
http://rorataspire.wordpress.com/2008/07/10/rails-composed_of/
http://api.rubyonrails.org/classes/ActiveRecord/Aggregations/ClassMethods.html#M001663
http://opensoul.org/2006/11/16/making-code-composed_of-code-more-useful
composed_of 感覺就是用來把妳一些 field 在弄成一個 object, 當然也就可以拿這個 value object 產生出新的 object, 也可以用在find 裡面當條件用
1. class Person < ActiveRecord::Base
2. composed_of :address,
3. :class_name => "Address",
4. :mapping => [%w(address_street street),
5. %w(address_city city),
6. %w(address_state state),
7. %w(address_country country)]
8.
9. class Address
10. attr_accessor :street, :city, :state, :country
11. def initialize(street, city, state, country)
12. @street = street
13. @city = city
14. @state = state
15. @country = country
16. end
17. end
- person.address = Address.new(...)
- person.save
這不會更新person的city字段,因為composed_of()的值對象被認為是immutable的,而只有new一個Address對象才能保存
- person.address.city = "LA"
- person.save
class UserData
attr_accessor :name
def initialize(name)
@name = name
end
end
class User < ActiveRecord::Base
composed_of :user_data, :mapping =>%w(name name) <= 其實是這樣 ["name", "name"]
end
現在就可以用這樣了
>> u = UserData.new('ilake')
=> #<UserData:0xb7197f28 @name="ilake">
>> User.find(:all, :conditions => {:user_data => u})
=> [#<User id: 5, name: "ilake"]
標籤:
composed_of,
data object,
model
2008年10月29日 星期三
module_eval,class_eval,singleton
http://onestepback.org/articles/10things/page027.html
http://my.donews.com/idlecat/2006/08/20/IpzenftEYkWGFjJpxPTDTJTCDOGKqTPzCaPZ/llllll
http://blackanger.blog.51cto.com/140924/84057
http://fcamel.twbbs.org/archives/2008/04/07/474/
http://tw.myblog.yahoo.com/weijenlu/article?mid=99&prev=109&next=-1
http://my.donews.com/idlecat/2006/08/20/IpzenftEYkWGFjJpxPTDTJTCDOGKqTPzCaPZ/llllll
http://blackanger.blog.51cto.com/140924/84057
http://fcamel.twbbs.org/archives/2008/04/07/474/
http://tw.myblog.yahoo.com/weijenlu/article?mid=99&prev=109&next=-1
class Module
def trace_attr(sym)
self.module_eval <<-EOS <= 也可以說是動態產生 method 的方法
def #{sym}
printf "Accessing %s with value %s\n",
"#{sym}", @#{sym}.inspect
@#{sym}
end
EOS
end
end
class Dog
trace_attr :name
def initialize(string)
@name = string
end
end
p Dog.new("Fido").name
class Test
end
code =<<-EOF
def hello_module
'hello world, use module'
end
EOF Test.module_eval(code) <= 動態塞段 code 進去, method 就生了, 太神啦
p Test.new.hello_module()
Test.class_eval <<-END <= 有直接塞進class的 fu
def hello_class
' hello world, use class'
end
END
p Test.new.hello_class()
t = Test.new
class << t <= 可以直接塞method 進 t 這個 object
def hello_singleton
'hello singleton'
end
end
class << Test <= Test class也是 oject 當然也可以塞
def class_singleton
'class singleton'
end
end
class Announce < ActiveRecord::Base
require_dependency 'forum/forum_model_mixin'
include ForumModelMixin
end
module ForumModelMixin
def self.included(klass) <= klass可以知道是哪個 class include了這個lib
klass.class_eval do
has_many :forum_comments, :as => :forum
alias_method :old_destroy, :destroy
validates_presence_of :content, :subject, :user_id
def destroy(r)
if r
old_destroy
else
update_attribute(:removed_at, Time.now) if !removed_at
end
end
end
end
end
標籤:
class_eval,
module_eval,
singleton
Dir,entries,glob
http://www.ruby-doc.org/core/classes/Dir.html
Dir.entries("#{RAILS_ROOT}/public/images/score/1")
=> ["victory_32.png", "..", "victory_128.png", "victory_64.png", "."]
Dir.glob("#{RAILS_ROOT}/public/images/score/1")
=> ["/home/lake/rails_app/iwakela/public/images/score/1"]
2008年10月28日 星期二
instance_variable_get,delegate
http://ihower.idv.tw/blog/archives/1719
http://blog.gugl.org/archives/41
http://www.ruby-doc.org/core/classes/Object.html#M000380
http://www.ruby-doc.org/core/classes/Module.html#M001677
http://www.ruby-doc.org/core/classes/Hash.html#M002868
KEYS_MAPPINGS.each do |key, value|
define_method key, lambda { <= 用來生 method 的 method
instance_variable_get('@hash')[value] <= 可以直接拿 @hash instance variable 的 值
}
end
KEYS_MAPPINGS = {
:ask => 'BSELL' , :bid => 'BBUY' ,
:change => 'CHANGE', :high => 'HIGH',
:target_id => 'STKID' , :target_name => 'STKNAME'
}
delegate_opts = MarketData::KEYS_MAPPINGS.keys.reject do |e|
e == :target_id || e== :target_name
end.push(:to => :market_data) <= 呼叫 名為 market_data的 instance _function, 一般常是 has_one :thing 的 thing, 不過一樣意思, 就是叫後面這個 function
delegate *delegate_opts <= delegate_opts = [:ask, :bid, :change, :high, {:to => :market_data}]
<= delegate *delegate_opts 就是 delegate :ask, :bid, :change, :high, :to => :market_data
<= delegate 可以一次傳入多個 parameter
def market_data(key=nil)
@market_data ||= MarketData.target(target_id)
key && @market_data ? @market_data[key] : @market_data <= 有傳 key 跟沒傳key return的東西不同
end
[User model]
has_one :profile
field = Profile.content_columns.inject([]) do |result, column| <= content_columns, 濾掉 _id, _count的那些
result << column.name
end.push(:to => :profile)
delegate *field
User.first.address <= 現在可以直接這樣用了
has_many,through,source,source_type,foregin_key,class_name
#我發表過forum的comments
has_many :forum_comments, :through => :forums, :source => :comments
#forum 裡有我的 comments的 forum, 找出 forum array
has_many :forums_has_comments,
:through => :comments,
:source => :record,
:source_type => 'Forum'
#我在forum 裡所有的comments, 找出 comments array
has_many :comments_in_forums,
:foreign_key => :user_id,
:class_name => 'Comment',
:conditions => {:record_type => 'Forum'}
標籤:
class_name,
foregin_key,
has_many,
source,
source_type,
through
2008年10月27日 星期一
length, mysql
User.find(:first, :order => "length(nickname) DESC")
SELECT * FROM `user` ORDER BY length(nickname) DESC LIMIT 1
SELECT * FROM `user` ORDER BY length(nickname) DESC LIMIT 1
Has_one with :source_type
http://www.javaeye.com/topic/129195
class Client < ActiveRecord::Base
has_many :contact_cards
has_many :business_contacts,
:through => :contact_cards,
:source => :contact, <= 跟 as => :this_item 的this_item 一樣
:source_type => 'Business'
end
class Business < ActiveRecord::Base
has_many :contact_cards, :as => :contact
end
class ContactCard < ActiveRecord::Base
belongs_to :client
belongs_to :contact, :polymorphic => true
end
User.first.business_cards <= 第一個user的contact card of bussiness category
標籤:
has_one,
source_type
2008年10月24日 星期五
有些form function 需要共用時, 可以放在layout
//隱藏在角落的 form
<% form_tag({:action => :show}, :class => 'show_stock') do %>
<%= hidden_field_tag :id %>
<% end %>
$(function(){
$('.layout.searchStockBtn').click(function() {
var val = $(this).parent().parent().find('.target_search').val();
var form = $('.show_stock'); <= 把 隱藏的 form 拿出來用
form.attr('action','<%= targets_show_path(:id => "") %>'); <= 把 form 的 action 變成其他 url
form.find('input').attr('name','id').val(val); <= 找值
form.get(0).submit();
return false;
});
2008年10月23日 星期四
svn, update
http://svnbook.red-bean.com/en/1.0/re28.html
You can also update your working copy to an older revision
You can also update your working copy to an older revision
svn update -r30
svn diff -rPREV
svn diff file_name -rPREV
svn log --limit
svn log --limit 2 main.css
svn cat -r5323 show.rhtml
svn merge -r7311:7389 svn://svn.icetech.com.tw/serac/youholder/branches/haruko
svn import earlybirds/ svn://bigcat.dlinkddns.com/eb/trunk
2008年10月21日 星期二
ruby-debugger
http://bashdb.sourceforge.net/ruby-debug.html#SEC_Top
http://thedaneshproject.com/posts/how-to-reload-your-bashrc-file/
We could create a file called .rdebugrc, and put these lines in
http://thedaneshproject.com/posts/how-to-reload-your-bashrc-file/
We could create a file called .rdebugrc, and put these lines in
set autoeval <= 不用再打 p 印 value
set autolist <= 自動列出所在行數
set autoreload <= 可以隨時加debugger, 他會自己reload
2008年10月20日 星期一
2008年10月17日 星期五
passenger, mod_rails
http://www.modrails.com/install.html
http://ihower.idv.tw/blog/archives/1741
http://nubyonrails.com/articles/ask-your-doctor-about-mod_rails
http://duckpunching.com/passenger-mod_rails-for-development-now-with-debugger
http://www.modrails.com/documentation/Users%20guide.html
http://ihower.idv.tw/blog/archives/1741
http://nubyonrails.com/articles/ask-your-doctor-about-mod_rails
http://duckpunching.com/passenger-mod_rails-for-development-now-with-debugger
http://www.modrails.com/documentation/Users%20guide.html
- Open a terminal, and type:
gem install passenger
- Type:
passenger-install-apache2-module
- /etc/apache2/apache2.conf
LoadModule passenger_module /usr/lib/ruby/gems/1.8/gems/passenger-2.0.3/ext/apache2/mod_passenger.so
PassengerRoot /usr/lib/ruby/gems/1.8/gems/passenger-2.0.3
PassengerRuby /usr/bin/ruby1.8
RailsEnv development <= development mode, default is production mode - /etc/apache2/sites-available/iwakela
- sudo ln -s /etc/apache2/sites-available/iwakela /etc/apache2/sites-enabled/001-iwakela
- /etc/init.d/apache2 restart/start/stop
- /etc/hosts 127.0.1.1 iwakela.local
# ... bottom of your development.rb
if File.exists?(File.join(RAILS_ROOT,'tmp', 'debug.txt'))
require 'ruby-debug'
Debugger.wait_connection = true
Debugger.start_remote
File.delete(File.join(RAILS_ROOT,'tmp', 'debug.txt'))
end
# add this rake file to your lib/tasks folder
# File: restart.rake
task :restart do
system("touch tmp/restart.txt")
system("touch tmp/debug.txt") if ENV["DEBUG"] == 'true'
end
rake restart DEBUG=true
rdebug -c
ServerAdmin iwakela@localhost
ServerName iwakela.local
DocumentRoot /home/lake/rails_app/iwakela/public
</virtualhost>
enable debugger
cgi,encode,decode,escape,unescape,escapeHTML
>> CGI::escapeHTML('&') <= HTML編碼
=> "&"
>> CGI::unescapeHTML('&')
=> "&"
>> CGI::escape('&') <= unicode
=> "%26"
>> CGI::unescape('%26')
=> "&"
ie, clone,timeout,setTimeout
http://blog.roodo.com/jaceju/archives/7231115.html
$.browser.msie <= check browser type
$(function () {
//setTimeout 可以確保程式在 DOM 完全更新後,再執行下一步的動作。
$('#copy').click(function () {
var $checkedValues = $('input.test:checked').clone();
if ($.browser.msie) {
setTimeout(function () { $checkedValues.attr('checked', true); }, 0);
}
$('#target').html('').append($checkedValues);
setTimeout(function () {
// 其他可能會對處理到 checkbox 的動作
}, 0);
});
});
標籤:
clone.timeout,
ie,
setTimeout
rescue_action_in_public, local_request, 取消 local request
http://api.rubyonrails.com/classes/ActionController/Rescue.html#M000615
http://blog.hendrikvolkmer.de/2007/3/8/http-referer-and-redirect_to-back
http://blog.hendrikvolkmer.de/2007/3/8/http-referer-and-redirect_to-back
[config/environments/development.rb]
config.action_controller.consider_all_requests_local = false
# force the request connect from outside
def local_request?
false
end
#有上面兩個條件rescue_action_in_public才可以在local測
def rescue_action_in_public(exception)
case exception
when ActionController::RoutingError
redirect_to home_url
else
super
end
end
<%= stylesheet_link_tag "defaults", "paginator", :cache => 'css_cache' %>
<%= javascript_include_tag "jquery", "jquery.corner.js", "jquerypngfix.js", :cache => 'js_cache' %>
上述的這些 :cache 功能 如果 client ip 是從 local來 就不會跑, 不會生出 css_cache.css 或 js_cache.js
2008年10月16日 星期四
javascript, scope, function
<script type="text/javascript">
var global_function = null; <= 宣告在這裡才是global的
(function($){
function local_funtion() { <= 這裡只是 local的
}
global_funcion = function() { <= 指定變數 成function
}
})(jQuery);
</script>
<script type="text/javascript">
global_function(); <= global這裡才叫的到
</script>
2008年10月15日 星期三
How to limit users to one vote per IP address
http://railsauthority.com/tutorial/how-to-limit-users-to-one-vote-per-ip-address
http://railsauthority.com/tutorial/how-to-obtain-the-ip-address-of-the-current-user
http://ithelp.ithome.com.tw/question/10011184
http://railsauthority.com/tutorial/how-to-obtain-the-ip-address-of-the-current-user
http://ithelp.ithome.com.tw/question/10011184
- # 以 regular expression 的設法來指定可執行的 IP 或範圍
- unless request.env['HTTP_X_REAL_IP'] =~ /^192\.168\.1\.(101|204|77|9)$|^168\.95\.1\./
- render :text => '不准看!'
- end
2008年10月12日 星期日
layout, select_layout
layout :select_layout
def select_layout
case action_name
when 'action1', 'action2'
'layout1'
when 'action3'
'layout2'
end
end
標籤:
layout,
select_layout
image_tag, path, url
http://api.rubyonrails.com/classes/ActionView/Helpers/AssetTagHelper.html
ActionController::Base.asset_host = "assets.example.com"
image_tag("rails.png")
=> <img src="http://assets.example.com/images/rails.png" alt="Rails" />
stylesheet_link_tag("application")
=> <link href="http://assets.example.com/stylesheets/application.css" media="screen" rel="stylesheet" type="text/css" />
ActionController::Base.asset_host = Proc.new { |source| "http://assets#{rand(2) + 1}.example.com" }
image_tag("rails.png")
=> <img src="http://assets2.example.com/images/rails.png" alt="Rails" />
stylesheet_link_tag("application")
=> <link href="http://assets1.example.com/stylesheets/application.css" media="screen" rel="stylesheet" type="text/css" />
ActionController::Base.asset_host = Proc.new { |source|
if source.starts_with?('/images')
"http://images.example.com"
else
"http://assets.example.com"
end
}
image_tag("rails.png")
=> <img src="http://images.example.com/images/rails.png" alt="Rails" />
stylesheet_link_tag("application")
=> <link href="http://assets.example.com/stylesheets/application.css" media="screen" rel="stylesheet" type="text/css" />
ActionController::Base.asset_host = Proc.new { |source, request|
if request.ssl?
"#{request.protocol}#{request.host_with_port}"
else
"#{request.protocol}assets.example.com"
end
}
訂閱:
文章 (Atom)