attributes.rb 2.1 KB

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