这是indexloc提供的服务,不要输入任何密码
Skip to content

poppinss/macroable

Macroable

Extend class prototype in style 😎

travis-image appveyor-image coveralls-image npm-image

Macroable is a simple class that your classes can extend in order to expose an API for extending the class. Let's see how a class can be extended without Macroable first.

Traditional approach

class Foo {}
module.exports = Foo

Someone can extend it follows.

const Foo = require('./Foo')
Foo.prototype.greet = function () {
  return 'Hello!'
}

// or add getter as follow
Object.defineProperty(Foo.prototype, 'username', {
  get: function () {
    return 'virk'
  }
})

Using macroable it's simpler

const { Macroable } from 'macroable'

class Foo extends Macroable {
}

Foo._macros = {}
Foo._getters = {}

module.exports = Foo
const Foo = require('./Foo')

Foo.macro('greet', function () {
  return 'Hello!'
})

Foo.getter('username', function () {
  return 'virk'
})

You can see the API is simpler and less verbose. However, their are couple more benefits to using Macroable.

  1. You can add singleton getters, which are evaluated only once and then cached value is returned.
  2. Cleanup all macros and getters added using Macroable.

Installation

npm i macroable

Usage

const { Macroable } from 'macroable'

class Foo extends Macroable {
}

Foo._macros = {}
Foo._getters = {}

module.exports = Foo

API

macro(name, callback) => void

Add a function to the prototype

Foo.macro('greet', function (name) {
  return `Hello ${name}!`
})

hasMacro(name) => boolean

Find if macro exists.

Foo.hasMacro('greet')

getter(name, callback, isSingleton?) => void

Add getter to the prototype and optionally make it singleton.

Foo.getter('username', function () {
  return 'virk'
}, true)

hasGetter(name) => boolean

Find if getter exists.

Foo.hasGetter('greet')

hydrate

Remove all macros and getters added using Macroable.

Foo.getter('username', function () {
  return 'virk'
}, true)

Foo.hydrate()

Foo.hasGetter('username') // false

Change log

The change log can be found in the CHANGELOG.md file.

Contributing

Everyone is welcome to contribute. Please go through the following guides, before getting started.

  1. Contributing
  2. Code of conduct

Authors & License

thetutlage and contributors.

MIT License, see the included MIT file.

About

Extend classes from outside in using Macros and getters

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Sponsor this project

 

Packages

No packages published

Contributors 3

  •  
  •  
  •