Skip to content

Instantly share code, notes, and snippets.

View Hampei's full-sized avatar

Henk van der Veen Hampei

View GitHub Profile
@Hampei
Hampei / paperclip_s3_fix.rb
Created February 7, 2012 13:38
interpolation for the url when storing paperclip attachments on s3 that works independent of where your bucket is located.
# normally paperclip uses the server/bucket/location format, but that breaks when you have a eu bucket.
# This one works for all buckets.
# put in an initializer (or somewhere else) and add this to has_attached_file params
# :url => ':s3_url',
Paperclip.interpolates(:s3_url) { |attachment, style|
"#{attachment.s3_protocol}://#{attachment.bucket_name}.s3.amazonaws.com/#{attachment.path(style).gsub(%r{^/}, "")}"
}
@Hampei
Hampei / redirect_from_www.rb
Created March 14, 2012 19:22
rails rack middelware - redirect from www.site.com to site.com
# in application.rb add
# config.middleware.insert 0, "RedirectFromWww" # first, so you don't need a certificate for the www. version
class RedirectFromWww
def initialize(app)
@app = app
end
def call(env)
request = Rack::Request.new(env)
if request.host.starts_with?("www.")
@Hampei
Hampei / from-replace-element.js.coffee
Created May 31, 2012 12:25
rails jquery coffeescript to throw remote-form reponse into a given element.
# response-html of forms replace the innerHTML of given element.
# usage <form data-remote='true' data-replace-element='#replace_my_contents'>...
$(document).on("ajax:success", "form[data-replace-element]", (el, data, status, xhr) ->
$($(this).data('replace-element')).html(data);
);
@Hampei
Hampei / repeat_last.js.coffee
Created June 16, 2012 21:27
jquery code to add repeating form parts. Usually for an array of items. Adds a link to add another row.
# Use for serialized Array attributes, to add a link to add rows for it in the form.
# Last child is saved and appended on click.
# .field.repeat_last{data: {'link-name' => 'add item'}}
# .item
# = f.text_field :name
# = f.text_field :url
$(->
$('form .repeat_last').map(->
el = $(this)
last_child = el.find('>*:last-child').clone()
@Hampei
Hampei / fields_for_array_of_hashes.rb
Created June 16, 2012 21:41
Form helper for serialised attributes of type array-of-hashes.
module ActionView
module Helpers
class FormBuilder
# - f.fields_for_array_of_hashes :links do |lnk|
# .item
# = lnk.text_field :name
# = lnk.text_field :url
def fields_for_array_of_hashes(record_name, record_object = nil, options = {}, &block)
@object.send(record_name).each do |e|
e = OpenStruct.new(e)
@Hampei
Hampei / copy_jquery_on_event_handlers.js
Last active October 13, 2015 07:27
copy delegated jquery events from one element to another
function copy_jquery_on_event_handlers(source, target) {
$.each(['click', 'submit', 'ajax:beforeSend', 'ajax:complete'], function(i, event_type) {
$.each($._data(source, 'events')['click'], function(j, jqe_spec) {
if (jqe_spec.selector != undefined)
$(target).on(event_type, jqe_spec.selector, jqe_spec.handler);
});
// browser support: chrome, safari, firefox, opera, ie9+, ieMobile10+ (Opera Mini not supported)
// No external libraries needed.
// calls fn on all current and future elements matching selector within the first element matching container_selector.
// find_with_mutations('.container', '.element', function(el) { })
window.find_with_mutations = function(container_selector, selector, fn) {
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
[].slice.call(mutation.addedNodes).forEach(function(el) {
if (el.nodeType !== 1) return;
// Turns all textareas into medium-editors
// requires:
// - Medium-Editor
// - jQuery (can be easily rewritten without)
// - find_with_mutations: https://gist.github.com/hampei/7620643
// - sync_node_html_to_form_field: https://gist.github.com/hampei/7620825
window.textareas_to_medium_editor = function() {
find_with_mutations('form', 'textarea', function(el) {
el.style.display = 'none'; // hide the textarea
editor = $('<div />'); // create editor element
// keeps the value of formfield set to html contents below target
window.sync_node_html_to_form_field = function(node, field) {
var observer = new MutationObserver(function(mutations) {
field.value = node.innerHTML;
});
observer.observe(node, { characterData: true, childList: true, subtree: true });
}
@Hampei
Hampei / xhr_aware_responder.rb
Last active August 29, 2015 14:06
xhr aware responder
# Will render the the show method instead of redirecting when the action is an ajax request.
# Also adds an options xhr_show to render instead of show.
class XhrAwareResponder < ActionController::Responder
protected
def navigation_behavior(error)
if get?
raise error
elsif has_errors? && default_action
render action: default_action, layout: options[:layout]
elsif controller.request.xhr?