Skip to content

Instantly share code, notes, and snippets.

View hopsoft's full-sized avatar

Nate Hopkins hopsoft

View GitHub Profile
@hopsoft
hopsoft / application_helper.rb
Last active August 29, 2015 14:25
JavaScript Modules Tag Helper
# app/helpers/application_helper.rb
module ApplicationHelper
def javascript_modules_tag
paths = Dir[
Rails.root.join("app/assets/javascripts/modules/**/*"),
Rails.root.join("lib/assets/javascripts/modules/**/*"),
Rails.root.join("vendor/assets/javascripts/modules/**/*")
]
@hopsoft
hopsoft / application.html.erb
Last active August 29, 2015 14:25
JavaScript Modules Layout
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<%= stylesheet_link_tag 'application', media: 'all' %>
<%= csrf_meta_tags %>
</head>
<body>
<%= yield %>
@hopsoft
hopsoft / main.js
Last active August 29, 2015 14:25
Modular JavaScript in Rails
// app/assets/javascripts/main.js
require([modules.lodash,], function (_) {
console.log(_);
});
@hopsoft
hopsoft / example.js
Created July 18, 2015 12:13
Example Module
// app/assets/javascripts/modules/example.js
define([modules.lodash], function (_) {
return "This is an example.";
});
@hopsoft
hopsoft / application.js
Last active August 29, 2015 14:25
Application JavaScript Manifest
// app/assets/javascripts/application.js
//= require jquery
//= require jquery-ujs
//= require main
@hopsoft
hopsoft / monkeypatch.rb
Created January 11, 2011 06:17
Monkeypatch - Illustrates how to re-open a class and redefine existing functionality
# define original class
class Example
def say_hello
puts "hello"
end
end
# re-open the class and monkeypatch some of its existing functionality
@hopsoft
hopsoft / open_classes.rb
Created January 11, 2011 05:25
Open Classes - Illustrates how to re-open a class in Ruby
# define original class
class Example
def say_hello
puts "hello"
end
end
# re-open the class
@hopsoft
hopsoft / namespace.rb
Created January 11, 2011 06:31
Namespace - Illustrates how to use modules for namespacing
# create a namespace to avoid naming collisions
module Example
class String
def length
100
end
end
end
@hopsoft
hopsoft / kernel_method.rb
Created January 11, 2011 16:12
Kernel Method - Illustrates how to add functionality to all objects
# add a kernel method to make it available to all objects
# this example also serves to illustrate that everything in Ruby is an object
module Kernel
def say_hello
puts "hello from #{self.class.name}"
end
end
@hopsoft
hopsoft / dynamic_dispatch.rb
Created January 11, 2011 18:05
Dynamic Dispatch - Illustrates how to invoke methods that are unknown at design time
# add methods that provide the ability
# to dynamically call unknown methods on objects
def invoke(object, method_name)
object.send(method_name)
end
def invoke_with_args(object, method_name, *args)
object.send(method_name, *args)
end