在自己的環境下執行 bundle exec rails c 時,
出現下列錯誤:
rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- bundler/setup (LoadError)
後來找了一下google 才找到解法:
bundle install --binstubs
詳細解說:
2016年2月18日 星期四
2016年2月3日 星期三
[Rails] 運用 Net::HTTP and URI
http = if Recaptcha.configuration.proxy
proxy_server = URI.parse(Recaptcha.configuration.proxy)
Net::HTTP::Proxy(proxy_server.host, proxy_server.port, proxy_server.user, proxy_server.password)
else
Net::HTTP
end
query = URI.encode_www_form(verify_hash)
uri = URI.parse(Recaptcha.configuration.verify_url + '?' + query)
http_instance = http.new(uri.host, uri.port)
http_instance.read_timeout = http_instance.open_timeout = options[:timeout] || DEFAULT_TIMEOUT
if uri.port == 443
http_instance.use_ssl = true
http_instance.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
request = Net::HTTP::Get.new(uri.request_uri)
http_instance.request(request).body URI.encode_www_form: 把ruby hash 變成 string
ex: URI.encode_www_form(sss: '123', ggg: '456') => sss=123&ggg=456
URI.parse: 把網址變成物件.
設定 http_instance timeout 時間
http_instance.read_timeout = http_instance.open_timeout = 3 (seccond)
超出時間會拋出 Timeout::Error
[Rails] require: cannot load such file -- bundler/setup (LoadError)
Error messages : require: cannot load such file -- bundler/setup (LoadError)
如果出現以上訊息.
請執行下列方式.
remove Gemfile.lock
bundle install
bundle exec rake rails:update:bin
如果出現以上訊息.
請執行下列方式.
remove Gemfile.lock
bundle install
bundle exec rake rails:update:bin
2016年1月26日 星期二
Ruby &block lambda proc yield 使用
基本 Lambda
hello = lambda { puts "Hello" }
hello.call
Result : Hello
log = lamba { |str| puts "[Log] #{str}"}
log.call ("Test message")
Result : [Log] Test message
Lambda Factory 模式
def times_n (n)
lambda { |x| x * n }
end
a=times_n(10)
a.call(5)
Result : 50
b=times_n(15)
b.call(10)
Result : 150
[1,2,3].collect(&b)
def my_lambda (&aBlock)
aBlock
end
b = my_lambda { puts "Hello world !" }
b.call
Result : Hello world !
下列三個相等
b = Proc.new {|x| puts x }
b = proc {|x| puts x }
b = lambda {|x| puts x}
proc 與 lambda 差異
add_lambda = lambda {|x , y| x + y}
add_lambda.call(4)
Result : ArgumentError: wrong number of arguments (1 for 2)
接收程式碼區塊的方法
def call_twice
puts "I'm about to call your block"
yield
puts "I'm about to call your block again"
yield
end
call_twice { puts "callback block." }
Result :
I'm about to call your block
callback block.
I'm about to call your block again
callback block.
hello = lambda { puts "Hello" }
hello.call
Result : Hello
log = lamba { |str| puts "[Log] #{str}"}
log.call ("Test message")
Result : [Log] Test message
Lambda Factory 模式
def times_n (n)
lambda { |x| x * n }
end
a=times_n(10)
a.call(5)
Result : 50
b=times_n(15)
b.call(10)
Result : 150
[1,2,3].collect(&b)
Result :
[
[0] 150,
[1] 300,
[2] 450
]
Block 區塊建立與呼叫
sub_block = lambda { | x | puts x }
sub_block.call ('Hi')
Result : Hi
def my_lambda (&aBlock)
aBlock
end
b = my_lambda { puts "Hello world !" }
b.call
Result : Hello world !
下列三個相等
b = Proc.new {|x| puts x }
b = proc {|x| puts x }
b = lambda {|x| puts x}
proc 與 lambda 差異
add_lambda = lambda {|x , y| x + y}
add_lambda.call(4)
Result : ArgumentError: wrong number of arguments (1 for 2)
add_lambda.call(4,5,6)
Result : ArgumentError: wrong number of arguments (3 for 2)
add_proc = proc {|x,y| x + y }
add_proc.call(4)
Result : ArgumentError: wrong number of arguments (1 for 2)
add_proc.call(4,5,6)
Ruby 1.8 Result : ArgumentError: wrong number of arguments (3 for 2)
Ruby 1.9 Result : 9 #多餘的參數會變成 nil
接收程式碼區塊的方法
def call_twice
puts "I'm about to call your block"
yield
puts "I'm about to call your block again"
yield
end
call_twice { puts "callback block." }
Result :
I'm about to call your block
callback block.
I'm about to call your block again
callback block.
def repeat(n)
if block_given?
n.times { yield }
else
raise ArgumentError.new(" I can't repeat a block you don't give me !")
end
end
repeat(3) { puts "hi"}
Result :
hi
hi
hi
repeat(5)
Result : ArgumentError: I can't repeat a block you don't give me !
def call_twice
puts "Calling your block "
ret1 = yield ('first')
puts "Calling your block again"
ret2 = yield ('second')
puts "ret1: #{ret1} , ret2: #{ret2}"
end
call_twice {|x| x == 'first' ? 1 : 2}
Result :
Calling your block
Calling your block again
ret1: 1 , ret2: 2
將區塊參數連繫到變數
下列三個方式結果都相等
方法一
def repeat (n)
n.times { yield } if block_given?
end
repeat (2) { puts "Hi" }
方法二
def repeat (n , &block )
n.times { block.call } if block
end
repeat (2) { puts "Hi" }
方法三
def repeat (n , &block )
n.times { yield } if block
end
repeat (2) { puts "Hi" }
以上差異 主要是 可以 省略掉 Kernek#block_given? 的使用 .
def biggest (collection , &block )
block ? collection.select(&block).max : collection.max
end
array = [1 ,2 ,3 ,4 ,5]
biggest(array) { | i | i < 3 }
Result : 2
biggest(array) { |i| i !=5 }
Result : 4
biggest(array)
Result : 5
Ruby 1.9 以上 新寫法
proc = ->(a, *b, &block) {
p a
p b
block.call if block
}
proc.(1,2,3,4,5) { puts 'Yes' }
Result :
1
[2, 3, 4, 5]
Yes
很厲害的方式:
def my_if(condition, then_clause, else_clause)
if condition
then_clause.call
else
else_clause.call
end
end
5.times do |val|
my_if (val < 3),
-> { puts "#{val} is small" },
-> { puts "#{val} is big" }
end
Result:
0 is small
1 is small
2 is small
3 is big
4 is big
Ruby 1.9 以上 新寫法
proc = ->(a, *b, &block) {
p a
p b
block.call if block
}
proc.(1,2,3,4,5) { puts 'Yes' }
Result :
1
[2, 3, 4, 5]
Yes
很厲害的方式:
def my_if(condition, then_clause, else_clause)
if condition
then_clause.call
else
else_clause.call
end
end
5.times do |val|
my_if (val < 3),
-> { puts "#{val} is small" },
-> { puts "#{val} is big" }
end
Result:
0 is small
1 is small
2 is small
3 is big
4 is big
2016年1月7日 星期四
[Rails] ActiveRecord::Enum
神奇的 enum 功能.
http://edgeapi.rubyonrails.org/classes/ActiveRecord/Enum.html
可以用這個gem 取代 https://github.com/brainspec/enumerize
class Conversation < ActiveRecord::Base
enum status: [ :active, :archived ]
end
# conversation.update! status: 0
conversation.active!
conversation.active? # => true
conversation.status # => "active"
# conversation.update! status: 1
conversation.archived!
conversation.archived? # => true
conversation.status # => "archived"
# conversation.status = 1
conversation.status = "archived"
conversation.status = nil
conversation.status.nil? # => true
conversation.status # => nil
2015年10月28日 星期三
Rails 4 class method 使用 alias_attribute, alias_method_chain, delegate, mattr_accessor
很需要了解並且熟悉這些method 的用法
http://api.rubyonrails.org/classes/Module.html#method-i-mattr_accessor
http://api.rubyonrails.org/classes/Module.html#method-i-mattr_accessor
Methods
- A
- C
- D
- F
- M
- P
- Q
- R
2015年6月3日 星期三
An ActionDispatch::RemoteIp::IpSpoofAttackError 10.xx.xx.xx
發生環境 Ruby 1.9.3 and Rails 3.2.20
若是你要讓 10.xxx.xxx.xxx 的ip 可以通過驗證.
若是在 rails 4.0 以上, 可以用下列方式.
參考資訊: https://meta.discourse.org/t/all-of-my-internal-users-show-as-coming-from-127-0-0-1/6607
若是你要讓 10.xxx.xxx.xxx 的ip 可以通過驗證.
方法一:
config.action_dispatch.ip_spoofing_check = false
方法二:
class ActionDispatch::RemoteIp
self.send :remove_const, "TRUSTED_PROXIES"
TRUSTED_PROXIES = %r{
^127\.0\.0\.1$ |
^(172\.(1[6-9]|2[0-9]|3[0-1]) |
192\.168
x)\.
}
end
若是在 rails 4.0 以上, 可以用下列方式.
config.action_dispatch.trusted_proxies = %r{
^127\.0\.0\.1$ |
^(172\.(1[6-9]|2[0-9]|3[0-1]) |
192\.168
x)\.
}
參考資訊: https://meta.discourse.org/t/all-of-my-internal-users-show-as-coming-from-127-0-0-1/6607
2015年3月26日 星期四
Rails 3.2.20 redirecting class 內的 _compute_redirect_to_location
Rails 3.2.20 中的 redirecting.rb
/actionpack/lib/action_controller/metal/redirecting.rb
會什麼可以吃這麼多種設定呢?
/actionpack/lib/action_controller/metal/redirecting.rb
會什麼可以吃這麼多種設定呢?
# Examples:
# redirect_to :action => "show", :id => 5
# redirect_to post
# redirect_to "http://www.rubyonrails.org"
# redirect_to "/images/screenshot.jpg"
# redirect_to articles_url
# redirect_to :back
# redirect_to proc { edit_post_url(@post) }
def _compute_redirect_to_location(options)
case options
# The scheme name consist of a letter followed by any combination of
# letters, digits, and the plus ("+"), period ("."), or hyphen ("-")
# characters; and is terminated by a colon (":").
# The protocol relative scheme starts with a double slash "//"
when %r{^(\w[\w+.-]*:|//).*}
options
when String
request.protocol + request.host_with_port + options
when :back
raise RedirectBackError unless refer = request.headers["Referer"]
refer
when Proc
_compute_redirect_to_location options.call
else
url_for(options)
end.gsub(/[\0\r\n]/, '')
end
2015年2月24日 星期二
Devise Issue: “[17] is not a symbol” [duplicate]
若是升級devise 時, 在舊版與新版中切換, 會碰上一個error:
is not a symbol” [duplicate]
原因是 devise 版本不同, 造成的 session 內容不同.
For devise<=2.2.3,
session["warden.user.player.key']=["Player", [player_id], "somehashhere"]
For devise>=2.2.4
session["warden.user.player.key']=[[player_id], "somehashhere"]
若是要舊版兼容新版, 就必須在 application_controller 加入下列code :
參考來源
is not a symbol” [duplicate]
原因是 devise 版本不同, 造成的 session 內容不同.
For devise<=2.2.3,
session["warden.user.player.key']=["Player", [player_id], "somehashhere"]
For devise>=2.2.4
session["warden.user.player.key']=[[player_id], "somehashhere"]
若是要舊版兼容新版, 就必須在 application_controller 加入下列code :
before_filter :fix_session
def fix_session
key = session["warden.user.player.key"]
if key && key.is_a?(Array) && key[0].is_a?(Array)
session["warden.user.player.key"].unshift('Player')
end
end 參考來源
2015年2月3日 星期二
Rails :dependent => :destroy VS :dependent => :delete_all
看來使用
:dependent => :destroy
會是一筆一筆撈出來 destroy
而使用
:dependent => :delete_all
效率看起來會比較高.
來源: http://stackoverflow.com/questions/2797339/rails-dependent-destroy-vs-dependent-delete-all
:dependent => :destroy
會是一筆一筆撈出來 destroy
而使用
:dependent => :delete_all
效率看起來會比較高.
來源: http://stackoverflow.com/questions/2797339/rails-dependent-destroy-vs-dependent-delete-all
2015年1月29日 星期四
[Ruby on Rails] development 環境增加 basic_auth_website .
在測試環境可以加這個. 來輸入basic_auth_for_web
before_filter :basic_auth_website if Rails.env.development?
def basic_auth_website
nm = 'test'
pw = "test_#{Rails.env}"
authenticate_or_request_with_http_basic("Application") do |name, password|
name == nm && password == pw
end
end
2014年12月19日 星期五
[rails] USE Index in db query .
看到一篇文章:Using indexes in rails: Index your associations
題到因為 order by 與 where 不同 index , 但是只想取出 limit 100 資料時, 就可以強制使用 Use index 去先讓 order by 的欄位排序後 取出 100 筆 , 這樣會比較快.
當然最完美解法是, 增加 排序欄位與條件欄位的 index .
題到因為 order by 與 where 不同 index , 但是只想取出 limit 100 資料時, 就可以強制使用 Use index 去先讓 order by 的欄位排序後 取出 100 筆 , 這樣會比較快.
當然最完美解法是, 增加 排序欄位與條件欄位的 index .
def self.use_index(index)
from("#{self.table_name} USE INDEX(#{index})")
end
2014年12月18日 星期四
[Ruby on Rails] 如何偵測一個method 是否存在並且使用它.
大概就是這樣啦:
resource.try_outside_rails(:phone_number)
class Object
def try_outside_rails(meth)
self.send(meth.to_sym) if self.respond_to?(meth.to_sym)
end
end
resource.try_outside_rails(:phone_number)
2014年11月17日 星期一
How to stub an IP in Ruby on Rails, RSpec Version 3 ?
在 Rspec 2:
ActionDispatch::Request.any_instance.stub(:remote_ip).and_return("192.168.0.1")
在 Rspec 3:
allow_any_instance_of(ActionDispatch::Request).to receive(:remote_ip).and_return("192.168.99.225")
2014年11月13日 星期四
手動安裝 gem .
來源: http://stackoverflow.com/questions/8991963/why-does-therubyracer-fails-to-build-on-my-debian
- Clone therubyracer's source
git clone https://github.com/cowboyd/therubyracer.git - Checkout tag v0.9.8
git checkout v0.9.8 - Change version number in
./lib/v8/version.rbto0.9.9 - Build the gem
gem build therubyracer.gemspec - Install the gem
gem install therubyracer-0.9.9.gem
2014年11月12日 星期三
ActiveRecord serialize field broken .
在 ActiveRecord 中的一個 model.
當中有個 serialize 的欄位, 居然吐出一個 很奇怪格式.
{
:coder => #<ActiveRecord::Coders::YAMLColumn:0x000000085d7ea8 @object_class=Object>,
:value => 'xxx',
:serialized => :serialized
}
, 令我百思不得其解.
最後居然是, 在執行此model 前先執行 , Product.undefine_attribute_methods , 這樣居然就好了.
{
:id => 2,
:name => "yoyo2",
:anchor => "yoyo2",
:settings => {
:coder => ActiveRecord::Coders::YAMLColumn:0x000000085d7ea8 @object_class=Object>,
:value => "---\n:relay:\n :Default: http://yoyo.com\n",
:state => :serialized
},
:created_at => Tue, 08 Apr 2014 05:36:58 UTC +00:00,
:updated_at => Wed, 12 Nov 2014 03:42:59 UTC +00:00
}
2014年10月2日 星期四
Ruby 中 class 與 module 的差異.
來源: http://stackoverflow.com/questions/151505/difference-between-a-class-and-a-module
想像一下~ module 就像是 library , 可以被其他 classs include or extend .
想像一下~ module 就像是 library , 可以被其他 classs include or extend .
╔═══════════════╦═══════════════════════════╦═════════════════════════════════╗
║ ║ class ║ module ║
╠═══════════════╬═══════════════════════════╬═════════════════════════════════╣
║ instantiation ║ can be instantiated ║ can *not* be instantiated ║
╟───────────────╫───────────────────────────╫─────────────────────────────────╢
║ usage ║ object creation ║ mixin facility. provide ║
║ ║ ║ a namespace. ║
╟───────────────╫───────────────────────────╫─────────────────────────────────╢
║ superclass ║ module ║ object ║
╟───────────────╫───────────────────────────╫─────────────────────────────────╢
║ consists of ║ methods, constants, ║ methods, constants, ║
║ ║ and variables ║ and classes ║
╟───────────────╫───────────────────────────╫─────────────────────────────────╢
║ methods ║ class methods, ║ module methods, ║
║ ║ instance methods ║ instance methods ║
╟───────────────╫───────────────────────────╫─────────────────────────────────╢
║ inheritance ║ inherits behavior and can ║ No inheritance ║
║ ║ be base for inheritance ║ ║
╟───────────────╫───────────────────────────╫─────────────────────────────────╢
║ inclusion ║ cannot be included ║ can be included in classes and ║
║ ║ ║ modules by using the include ║
║ ║ ║ command (includes all ║
║ ║ ║ instance methods as instance ║
║ ║ ║ methods in class/module) ║
╟───────────────╫───────────────────────────╫─────────────────────────────────╢
║ extension ║ can not extend with ║ module can extend instance by ║
║ ║ extend command ║ using extend command (extends ║
║ ║ (only with inheritance) ║ given instance with singleton ║
║ ║ ║ methods from module) ║
╚═══════════════╩═══════════════════════════╩═════════════════════════════════╝
2014年9月24日 星期三
[Rails] Use ActiveModel 's Callbacks .
使用結果如下:
class TestCallback
extend ActiveModel::Callbacks
define_model_callbacks :create
def create
run_callbacks :create do
puts 'Run run_callback'
end
end
before_create :action_before_create
def action_before_create
puts 'Run action_before_create'
end
end
TestCallback.new.create
Result:
Run action_before_create
Run run_callback
rails respond_to 與 method_missing 使用.
來源: http://blog.enriquez.me/2010/2/21/dont-forget-about-respond-to-when-implementing-method-missing/
更好實現Proxy 的方法.
class Proxy
def initialize(subject)
@subject = subject
end
def method_missing(method)
@subject.send(method)
end
end
proxy = Proxy.new(Time)
proxy.respond_to?(:now) # => false
proxy.now # => Fri Feb 05 00:34:53 -0500 2010
更好實現Proxy 的方法.
class Proxy
def initialize(subject)
@subject = subject
end
def method_missing(method)
if @subject.respond_to?(method)
@subject.send(method)
else
super(method)
end
end
def respond_to?(method, include_private = false)
super || @subject.respond_to?(method, include_private)
end
end
proxy = Proxy.new(Time)
proxy.respond_to?(:now) # => true
proxy.now # => Fri Feb 05 00:34:53 -0500 2010
2014年9月19日 星期五
[Ruby] STDIN、STDOUT、STDERR和$stdin、$stdout、$stderr
STDIN、STDOUT、STDERR 都是 IO class 不能更動.
$stdin、$stdout、$stderr 是可以更動的.
$stdout 與 STDOUT 一開始都是輸出到螢幕.
$stdout = open('output_file','w')
#將會輸出到 output_file 檔案.
$stdout = STDOUT
#又會回到螢幕上.
執行結果:
$ ls
std.rb
$ ruby std.rb
$ ls
std.rb err.txt out.txt
$ cat err.txt
something to stderr
$ cat out.txt
normal output
參考資訊:Link
$stdin、$stdout、$stderr 是可以更動的.
$stdout 與 STDOUT 一開始都是輸出到螢幕.
$stdout = open('output_file','w')
#將會輸出到 output_file 檔案.
$stdout = STDOUT
#又會回到螢幕上.
# std.rb
$stdout.reopen("out.txt", "w")
$stderr.reopen("err.txt", "w")
puts 'normal output'
warn 'something to stderr'
執行結果:
$ ls
std.rb
$ ruby std.rb
$ ls
std.rb err.txt out.txt
$ cat err.txt
something to stderr
$ cat out.txt
normal output
參考資訊:Link
訂閱:
文章 (Atom)