attributes.rb 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #---
  2. # Excerpted from "Agile Web Development with Rails",
  3. # published by The Pragmatic Bookshelf.
  4. # Copyrights apply to this code. It may not be used to create training material,
  5. # courses, books, articles, and the like. Contact us if you are in doubt.
  6. # We make no guarantees that this code is fit for any purpose.
  7. # Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book information.
  8. #---
  9. $: << File.dirname(__FILE__)
  10. require "connect"
  11. require "logger"
  12. require "pp"
  13. #ActiveRecord::Base.logger = Logger.new(STDERR)
  14. require "rubygems"
  15. require "active_record"
  16. class LineItem < ActiveRecord::Base
  17. end
  18. LineItem.delete_all
  19. LineItem.create(:quantity => 1, :product_id => 27, :order_id => 13, :unit_price => 29.95)
  20. LineItem.create(:quantity => 2, :unit_price => 29.95)
  21. LineItem.create(:quantity => 1, :unit_price => 44.95)
  22. result = LineItem.find(:first)
  23. p result.quantity
  24. p result.unit_price
  25. result = LineItem.find_by_sql("select quantity, quantity*unit_price " +
  26. "from line_items")
  27. pp result[0].attributes
  28. result = LineItem.find_by_sql("select quantity,
  29. quantity*unit_price as total_price " +
  30. "from line_items")
  31. pp result[0].attributes
  32. p result[0].total_price
  33. sales_tax = 0.07
  34. p result[0].total_price * sales_tax
  35. class LineItem < ActiveRecord::Base
  36. def total_price
  37. Float(read_attribute("total_price"))
  38. end
  39. CUBITS_TO_INCHES = 2.54
  40. def quantity
  41. read_attribute("quantity") * CUBITS_TO_INCHES
  42. end
  43. def quantity=(inches)
  44. write_attribute("quantity", Float(inches) / CUBITS_TO_INCHES)
  45. end
  46. end
  47. p result[0].quantity
  48. result[0].quantity = 500
  49. p result[0].save