Prev | Current Page 254 | Next

Kevin Marshall, Chad Pytel, and Jon Yurek

"Pro Active Record: Databases with Ruby and Rails"

You can
still use plug-ins meant for Rails with Active Record apart from Rails, but you??™ll have to do the work of initializing
them yourself, much like you have to worry about setting up your own database connection. In practice,
it??™s about as simple as that as well: just require the init.rb file in the plug-in and most of the time that
should be enough.
Extending Active Record the Easy Way
The easiest way to add functionality to Active Record is to open the ActiveRecord::Base class
and define some new functions. For example, we can add a method, which will be available to
all models, that can greet the user and display its class name and ID:
CHAPTER 5 ?–  BONUS FEATURES 109
class ActiveRecord::Base
def hello_world
"Hello from #{class.name}, World! My ID is #{id}."
end
end
cow = Cow.find_by_name("Bessie")
cow.hello_world # Hello from Cow, World! My ID is 5.
The hello_world method is now available to all Active Record objects. If we added our
code into a file called ar_hello_world.rb, all we have to do to make sure it gets included is add
the following line to our program:
require "ar_hello_world"
Yes, modifying Active Record classes really is that simple.


Pages:
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266