Skip to content

Instantly share code, notes, and snippets.

@doc """
Asserts based on pattern matching.
Example: check if collection contains element that matches the pattern
assert_match %{body: "lorem"} in messages
assert_match %{id: ^id} in response["users"]
"""
defmacro assert_match({:in, _, [left, right]} = assertion) do
code = Macro.escape(assertion)
@doc """
Validate each array element with validator
Examples
iex> changeset
...> |> validate_each(:emails, &validate_email)
...> |> validate_each(:phones, &validate_format(&1, &2, ~r/\d+/))
...> |> validate_each(:phones, &validate_length/3, is: 4)
"""
def validate_each(changeset, field, validator, opts) do
@teamon
teamon / .gitignore
Last active January 8, 2016 15:08
react + webpack + babel (es2015 + jsx + stage-0) starter
/node_modules
/bundle.js
/bundle.js.map
source "https://rubygems.org"
gem "grape"
gem "kaminari"
gem "grape-kaminari", "~> 0.1.8"
@teamon
teamon / munin-passenger
Last active August 29, 2015 14:03
Munin passeger 4 plugin
nobody ALL=(ALL) NOPASSWD:/usr/local/bin/passenger-status, /usr/local/bin/passenger-memory-stats
# config/initializers/instrumentation.rb
# Subscribe to grape request and log with Rails.logger
ActiveSupport::Notifications.subscribe('grape.request') do |name, starts, ends, notification_id, payload|
Rails.logger.info '[API] %s %s (%.3f ms) -> %s %s%s' % [
payload[:request_method],
payload[:request_path],
(ends-starts)*1000,
(payload[:response_status] || "error"),
payload[:x_organization] ? "| X-Org: #{payload[:x_organization]}" : "",
@teamon
teamon / .vimrc
Last active August 29, 2015 14:02
set number
set nowrap
set showbreak
set textwidth=100
set showmatch
set visualbell
set hlsearch
set smartcase
set ignorecase
@teamon
teamon / gist:6c82cf686291e61bc2fc
Last active August 29, 2015 14:01
Ruby 2.1 method return value use cases
private def foo # make one method private
instrumet def foo # calculates execution time
silent def foo # silences stdout/err output
cached def foo(args...) # caches each invokation with different arguments into redis
memoize def foo # memoizes return value in instance variable
module CachedDef
def cached(name)
meth = instance_method(name)
raise ArgumentError.new("cached can be used only for method with no arguments") if meth.arity != 0
alias_method "__cached_def_original__#{name}", name
class_eval <<-EOS
def #{name}
@__cached_def_cache__#{name} ||= __cached_def_original__#{name}
@teamon
teamon / post_representer.rb
Created May 7, 2014 18:25
Ruby representers without a library
module PostRepresenter
include Representer
using Representer
def basic(post)
select(post, :id, :name)
end
def details(post)
basic(post) & comments(post)