Guest User

Untitled

a guest
Jul 17th, 2018
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. # global constants
  2. ROOT = exports ? this
  3. ROOT.READ = 1
  4. ROOT.WRITE = 2
  5.  
  6.  
  7. # defines a property on an object/class
  8. Object::has = (name, options = {}) ->
  9. options['access'] ?= READ | WRITE
  10. options['default'] ?= null
  11. options['variable'] ?= '_' + name
  12. options['get'] ?= 'get_' + name
  13. options['set'] ?= 'set_' + name
  14.  
  15. readable = options['access'] & READ
  16. writeable = options['access'] & WRITE
  17.  
  18. getter = this[options['get']] or -> this[options['variable']] + ' (accessed through getter)'
  19. setter = this[options['set']] or (value) -> this[options['variable']] = value + ' (set through setter)'
  20.  
  21. config = {}
  22. config['writeable'] = writeable
  23. config['get'] = getter if readable
  24. config['set'] = setter if writeable
  25. config['configurable'] = no
  26. config['enumerable'] = yes
  27.  
  28. using_default_getter_or_setter = this[options['get']]? or this[options['set']]?
  29. @prototype[options['variable']] = options['default'] if using_default_getter_or_setter
  30. Object.defineProperty @prototype, name, config
  31.  
  32.  
  33. # TODO: Implement these.
  34. Object::has_one = (name, options) -> null
  35. Object::has_many = (name, options) -> null
  36. Object::belongs_to = (name, options) -> null
  37. Object::has_and_belongs_to_many = (name, options) -> null
  38.  
  39.  
  40. # define the class
  41. class Book
  42. @has 'uniqueID', access: READ, default: '010101010101'
  43. @has 'changed', access: WRITE
  44. @has 'title', default: 'New Book' # read and write by default
  45. @has 'author', default: 'Unknown'
  46. @has 'isbn'
  47.  
  48.  
  49. # run some tests
  50. book = new Book()
  51. console.log 'Default book title: ' + book.title
  52.  
  53. book.title = 'CoffeeScript Cookbook'
  54. console.log 'Title of book is: ' + book.title
  55.  
  56. book.uniqueID = "Test"
  57. console.log book.uniqueID
Add Comment
Please, Sign In to add comment