merqlove
merqlove
Reputation Top 1%
merqlove
8 Snippets  (103rd place)
Published
1 Channel
Created
1 Channel
Following
184 points  (163rd place)
Reputation
Junior Code Generator
Serious Code Generator
Serious Popular Coder
Junior Autobiographer
Serious Autobiographer
Serious Famous Coder
Junior Wise Coder

Recent Snippets See all snippets by merqlove

public by merqlove  207886  2  4  2

AngularJS / NodeWebkit logger service.

AngularJS / NodeWebkit logger service.: logger.coffee
'use strict';

angular.module('vc.messages')
.factory "logger", ['$log', 'NwService', ($log, NwService) ->
  log4js = require('log4js')

  log4js.configure {
    appenders: [
      {
        type: 'console'
        layout: {
          type: 'pattern'
          pattern: "%m%n"
        }
        category: 'console'
      },
      {
        type: 'file'
        absolute: true
        filename: NwService.dataPath() + '/app.log'
        category: 'file'
        maxLogSize: 1024*1024
        numBackups: 3
        layout: {
          type: 'pattern'
          pattern: "[%d %r] [%p] - %m%n"
        }
      },
    ]
    levels: {
      "[all]": "INFO",
      "console": NwService.isProduction() ? "OFF" : "DEBUG",
      "file": "ERROR"
    }
  }

  consoleLogger = log4js.getLogger('console')

  ['Trace','Debug','Info','Warn','Error','Fatal'].forEach (levelString) ->
    level = log4js.levels.toLevel(levelString)

    consoleLogger[levelString.toLowerCase()] = () ->
      return false unless consoleLogger.isLevelEnabled(level)
      args = Array.prototype.slice.call(arguments)
      switch levelString
        when 'Info', 'Warn'
          $log[levelString.toLowerCase()](args)
        else
          args.unshift(level)
          consoleLogger.log.apply(consoleLogger, args)

  return {
    file: log4js.getLogger('file')
    console: consoleLogger
  }
]

;

public by merqlove  2331  1  4  0

NgAnimate Mock in CoffeeScript

NgAnimate Mock in CoffeeScript: angular-animate-mock.coffee
# Converted JS from http://mgcrea.github.io/angular-strap

angular.module('ngAnimate', [])

.factory('$$animateReflow', ['$window', '$timeout', ($window, $timeout) ->
  requestAnimationFrame = $window.requestAnimationFrame ||
                          $window.webkitRequestAnimationFrame ||
                          (fn) ->
                            $timeout(fn, 10, false)


  cancelAnimationFrame = $window.cancelAnimationFrame       ||
                         $window.webkitCancelAnimationFrame ||
                         (timer) ->
                           $timeout.cancel(timer)

  (fn) ->
    id = requestAnimationFrame(fn)
    () ->
      cancelAnimationFrame(id)
])

;

public by Alexander Merkulov  2730  0  4  0

AngularJS service to work with Chef DataBags via Knife CLI.

AngularJS service to work with Chef DataBags via Knife CLI.: DataBagService.coffee
'use strict';

class DataBagService
  _exec = {}
  _tmp = {}
  _fs = {}
  _knife = ''

  constructor: (@$q) ->
    console.log 'DataBagService: constructor called'
    _exec = require('child_process').exec
    _tmp = require('tmp')
    _fs = require('fs')
    this.setKnifePath()

  setKnifePath:(path) ->
    _knife = path || 'RBENV_VERSION=2.0.0-p353 knife'

  getDataBagItem: (client, data_bag, item) ->
    return {} unless client && data_bag && item

    deferred = @$q.defer()

    _exec "#{_knife} data bag show #{data_bag} #{item} "+
          authString(client), (err, stdout, stderr) ->
            if err
              deferred.resolve(false)
              throw err
            else
              deferred.resolve(JSON.parse(stdout))

    return deferred.promise

  putDataBagItem: (client, data_bag, item) ->
    return {} unless client && data_bag && item

    deferred = @$q.defer()

    _tmp.file {postfix: '.json'}, (err, path, fd) ->
      if (err)
        _tmp.setGracefulCleanup()
        deferred.resolve(false)
        throw err

      _fs.writeFileSync path, JSON.stringify(item)

      _exec "#{_knife} data bag from file #{data_bag} #{path} "+
            authString(client), (err, stdout, stderr) ->
              if err
                deferred.resolve(false)
                throw err
              else
                deferred.resolve(true)

    return deferred.promise

  userName = (user) ->
    user.replace('-validator','')

  authString = (client) ->
    "-u #{client.user} "+
    "-k #{process.env.HOME}/.chef/#{client.user}.pem "+
    "--server-url #{client.base} "+
    "--secret-file #{secretFile(client.user)} "+
    "-F json"

  secretFile = (name) ->
    "#{process.env.HOME}/.chef/#{userName(name)}_secret "

angular.module('app.services')
.service 'DataBagService', [ '$q', DataBagService ]

;

public by merqlove  6624  13  4  3

Global Resolve for Angular ngRoute

Global Resolve for Angular ngRoute: routes.coffee
'use strict';

angular.module('app.routes')
.config(['$routeProvider', ($routeProvider) ->

    angular.extend({}, $routeProvider, {
      orgWhen: (path, route) ->
        route.resolve ||= {}
        route.resolve = _.merge(route.resolve, {
          chef: 'OrganizationCheckerProvider'
        })
        $routeProvider.when.call(this, path, route)
    })

    # Organizations

    .when('/organizations', {
        templateUrl: '/templates/organizations/index.html',
        controller: 'OrganizationsCtrl',
        controllerAs: 'orgs',
      })

    .when('/organizations/new', {
        templateUrl: '/templates/organizations/new.html',
        controller: 'OrganizationsNewCtrl',
        controllerAs: 'org',
      })
    .orgWhen('/organizations/:organizationId', {
        templateUrl: '/templates/organizations/show.html',
        controller: 'OrganizationsShowCtrl',
        controllerAs: 'org',
      })
    .orgWhen('/organizations/:organizationId/edit', {
        templateUrl: '/templates/organizations/edit.html',
        controller: 'OrganizationsEditCtrl',
        controllerAs: 'org',
      })
  ])

;

public by merqlove  3396  0  4  0

Angular $resource experience with Rails based API

Angular $resource experience with Rails based API: create_rails_api_request.coffee
# Create service for our factories. Don't blow .json extension. This is easiest path to get JSON request in AUTO mode.
angular.module("identityService", ["ngResource"])
.factory 'Identity', ($resource) ->
  $resource '/api/v1/identities/:id.json',
    { id:'@id' }

# Added update via PUT
@identities.config ($resourceProvider) ->
  $resourceProvider.defaults.actions.update = { method: 'PUT' }

# Run our test
@identities.controller 'RestaurantIndexCtrl', ($scope, Identity) ->  
  data = {
    identity: {
      user_id: 55
      provider: "vkontakte"
    }
  }
  
  Identity.save(data)
  Identity.update id:1, identity: {user_id:444}
  

;