Created
July 19, 2012 07:44
-
-
Save linjian/3141413 to your computer and use it in GitHub Desktop.
Initialize Variables for Rails Console
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Two scripts to initialize variables for rails console. | |
# I prefer the second one. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Solution 1: | |
# Puts it in ~/.irbrc | |
# then type '__init_vars_by_binding(binding).call' after rails console loaded. | |
if defined? ::Rails | |
def __init_vars_by_binding(binding) | |
Proc.new do | |
__quiet_name_error { binding.eval("user = User.first(:email => '[email protected]')") } | |
__quiet_name_error { binding.eval("account = user.account") } | |
end | |
end | |
def __quiet_name_error | |
yield | |
rescue NameError => e | |
# Be quiet | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Solution 2: | |
# Just puts it in ~/.irbrc, that's all, no more typing needed. | |
if defined? ::Rails | |
def __set_vars_for_main(name, value) | |
return if value.nil? | |
TOPLEVEL_BINDING.eval('self').instance_eval do | |
self.class_eval { attr_accessor name } | |
self.send("#{name}=", value) | |
end | |
end | |
def __without_name_error | |
yield | |
rescue NameError => e | |
nil | |
end | |
__set_vars_for_main(:user, __without_name_error { User.first(:email => '[email protected]') }) | |
__set_vars_for_main(:account, __without_name_error { user.account }) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment