Skip to content

Instantly share code, notes, and snippets.

View blocknotes's full-sized avatar
🎲
Why choose when I can launch a D6?

Mattia Roccoberton blocknotes

🎲
Why choose when I can launch a D6?
View GitHub Profile
@blocknotes
blocknotes / chaining.rb
Created August 13, 2017 10:59
Ruby - Static Method Chaining
# An implementation of static method chaining - like ActiveRecord, for example: Model.where( condition: true )
class Chain
attr_accessor :ref, :val
def initialize( ref, val = {} )
@ref = ref
@val = val
end
@blocknotes
blocknotes / random_stuff.md
Last active October 23, 2017 17:37
Ruby on Rails - Random stuff
  • Load rails app from irb: require_relative 'config/environment.rb' (after that Rails.application is available)
  • Translation key for a model (ex. MyModel): MyModel.model_name.i18n_key
  • Clean and recompile assets: rake assets:clean assets:clobber assets:precompile (preperate RAILS_ENV=production to set env)
  • Enable/disable cache in development: rake dev:cache
  • Dev routes: /rails/info/properties - /rails/info/routes
  • Search for notes comments ([TODO], [FIXME], etc.): rake notes
  • Dump/restore DB structure: rake db:structure:dump - rake db:structure:load
  • Funny method: ActionDispatch::IntegrationTest.i_suck_and_my_tests_are_order_dependent!
@blocknotes
blocknotes / application.rb
Created August 13, 2017 10:55
Ruby on Rails - after_initialize
# Rails - sometimes it's needed to execute some code before anything else but after Rails core is loaded. A good place to achieve this is using after_initialize in config/application.rb:
# ... config requires ...
module MyApp
class Application < Rails::Application
config.after_initialize do
# init code here...
end
end
end
@blocknotes
blocknotes / prepend.rb
Created August 13, 2017 10:53
Ruby - prepend
# Ruby offers different ways to extend classes / monkey patch / override methods.
# A good way to execute code before or after a method of a class is using prepend
class Test
def fun
puts 'Inside fun()'
end
end
Test.new.fun
@blocknotes
blocknotes / dsl.rb
Created August 13, 2017 10:52
Ruby - DSL / metaprogramming
# Set values in new block
class MyClass
attr_accessor :name, :val
def initialize
yield self if block_given?
end
end
MyClass.new do |obj|
@blocknotes
blocknotes / dry-validation_test1.rb
Last active July 5, 2018 18:33
Ruby - dry-validation gem examples
require 'dry-validation'
schema = Dry::Validation.Schema do
required(:name).filled
required(:age).maybe(:int?)
optional(:sex).value( included_in?: %w(M F) )
end
hash = { name: 'Jane', email: '[email protected]' }
hash[:age] = 21
@blocknotes
blocknotes / call_c_functions.rb
Created August 13, 2017 10:40
Ruby - Call C functions (with ffi gem)
require 'ffi'
# Example 1: libc - puts
module MyLib
extend FFI::Library
ffi_lib 'c'
attach_function :puts, [ :string ], :int
end