Created
March 18, 2011 19:08
-
-
Save andersonsp/876650 to your computer and use it in GitHub Desktop.
Rails 3 custom form builder implementing a simple color picker based on JQuery and CaryonBox plugin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
INSTALLATION | |
the rails application must have support for JQuery | |
get JQuery.Crayonbox.js at http://gelform.com/crayonbox-jquery-plugin/ | |
add the plugin JQuery.Crayonbox.js to /public/javascript folder | |
add the crayonbox css to /public/stylesheets folder | |
add color_picker_form_builder.rb to the /lib folder | |
add to the view or layout file: | |
<%= javascript_include_tag "jquery.crayonbox.js" %> | |
<%= stylesheet_link_tag jquery.crayonbox.css %> | |
Use in form builder | |
- builder.color_picker :color | |
- builder.color_picker :color, :available => [ "#ff6600", "#785f4b", "#56bb98", "#786575", "#000000" ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ColorPickerFormBuilder < ActionView::Helpers::FormBuilder | |
def color_picker(method, options={}) | |
default_colors = [ "#C0C0C0", "#FF6347", "#FFA500", "#FFFF00", "#7FFF00", "#00BFFF", "#C71585" ].freeze | |
selected_color = @object.send(method) | |
options[:available] ||= default_colors | |
sanitized_object_name ||= @object_name.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "") | |
sanitized_method_name ||= method.to_s.sub(/\?$/,"") | |
c_picker = "<input type=\"hidden\" id=\"id_#{sanitized_object_name}_#{sanitized_method_name}\" name=\"#{@object_name.to_s}[#{method.to_s}]\"/>" | |
c_picker << "<script type=\"text/javascript\">" | |
c_picker << "$('#id_#{sanitized_object_name}_#{sanitized_method_name}').crayonbox(" | |
c_picker << "{" | |
c_picker << "colors: new Array(#{options[:available].to_s.gsub(/^\[|\]$/, "")})" | |
c_picker << ",selected: '#{selected_color}'" if selected_color | |
c_picker << "}" | |
c_picker << "); " | |
c_picker << "</script>" | |
c_picker.html_safe | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment