code_junkie

override ActiveRecord attribute methods

Nov 13th, 2011
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. class Person < ActiveRecord::Base
  2. def name=(name)
  3. super(name.capitalize)
  4. end
  5. def name
  6. super().downcase # not sure why you'd do this; this is just an example
  7. end
  8. end
  9.  
  10. def name=(name)
  11. write_attribute(:name, name.capitalize)
  12. end
  13.  
  14. def name
  15. read_attribute(:name).downcase # No test for nil?
  16. end
  17.  
  18. def name=(name)
  19. self[:name] = name.capitalize
  20. end
  21.  
  22. def name
  23. self[:name].downcase
  24. end
  25.  
  26. class Post < ActiveRecord::Base
  27.  
  28. serialize :foo
  29.  
  30. def foo
  31. read_attribute(:foo)
  32. end
  33. end
  34.  
  35. ./script/plugin install git://github.com/chriseppstein/has_overrides.git
  36.  
  37. class Post < ActiveRecord::Base
  38.  
  39. has_overrides
  40.  
  41. module Overrides
  42. # put your getter and setter overrides in this module.
  43. def title=(t)
  44. super(t.titleize)
  45. end
  46. end
  47. end
  48.  
  49. $ ./script/console
  50. Loading development environment (Rails 2.3.2)
  51. >> post = Post.new(:title => "a simple title")
  52. => #<Post id: nil, title: "A Simple Title", body: nil, created_at: nil, updated_at: nil>
  53. >> post.title = "another simple title"
  54. => "another simple title"
  55. >> post.title
  56. => "Another Simple Title"
  57. >> post.update_attributes(:title => "updated title")
  58. => true
  59. >> post.title
  60. => "Updated Title"
  61. >> post.update_attribute(:title, "singly updated title")
  62. => true
  63. >> post.title
  64. => "Singly Updated Title"
Add Comment
Please, Sign In to add comment