Skip to content

Instantly share code, notes, and snippets.

@nickjacob
Last active August 29, 2015 14:17
Show Gist options
  • Save nickjacob/300c508732857ad42683 to your computer and use it in GitHub Desktop.
Save nickjacob/300c508732857ad42683 to your computer and use it in GitHub Desktop.
define_method in coffeescript
class ContentItem
constructor: (@type) ->
# implementation of ruby's
# `define_method`; simplifies
# metaprogramming/adding methods at runtime
@define_method: (name, fn) ->
# syntax shorthand for
# this.prototype[name] = function(/* arguments */){...}
# note that `fn` will be in instance context (bound)
@::[name] = (args...) -> fn.apply(@, args)
for t in ['book', 'article', 'list']
do (t) -> @define_method "is_#{t}", -> (@type is t)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment