ActiveScaffold jqplot and FieldSearch

Leave a comment

Every tried to use a graphic library with ActiveScaffold and fieldsearch?

Just a quick introduction how you may integrate jqplot Activescaffold and field_search.

Add a new layout which integrates jqplot

...
javascript_include_tag 'jquery.jqplot.min'
javascript_include_tag 'jqplot.highlighter.min'
javascript_include_tag 'jqplot.cursor.min'
javascript_include_tag 'my_chart_statistic'
stylesheet_link_tag 'jquery.jqplot.min'
...

Configure you Controller to disable all actions except field_search and configure field_search as you like:

layout "charts"
...
conf.list.pagination = false

conf.actions.exclude :show
conf.actions.exclude :update
conf.actions.exclude :create
conf.actions.exclude :search
conf.actions < {‘number’ => 1,
‘from’ => ”,
‘to’ => ”,
‘unit’ => “YEARS”,
‘range’ => ‘TODAY’,
‘opt’ => ‘PAST’},
:col2 => {‘opt’ => ‘%?’}
}

Override _list.html.erb view for your controller

<p class="filtered-message-graph" >
'human_conditions', :locals => {:columns => @filtered}) : as_(active_scaffold_config.list.filtered_message) %>

<div id=”my-chart” data-records=””>

 

Configure jqplot to displa your graph (my_chart_statistic.js in javascript dir)

$(document).ready(function(){
var update_chart = function() {
var records = $("#my-chart").data("records");
var bcsPlot = $.jqplot('my-chart', [records],
{
title:'',
axes:{
xaxis:{
label:'col1',
min: 0,
tickOptions: {
showGridline: false
}
},
yaxis:{
label:'col2',
min: 0,
max: 5,
ticks:[1.00, 1.50, 2.00, 2.50, 3.0, 3.50, 4.0, 4.5, 5.0],
tickOptions: {
formatString: '%.2f' // format string to use with the axis tick formatter
}
}
},
highlighter: {
show: true,
tooltipContentEditor: function (str, seriesIndex, pointIndex, plot) {

var col2 = plot.data[seriesIndex][pointIndex][2];
var col3 = plot.data[seriesIndex][pointIndex][3];
var col4 = plot.data[seriesIndex][pointIndex][4];

var html = “

col2: “;
html += col2;
html += “col3: “;
html += col3;
html += “col4: “;
html += col4;
html += “

“;

return html;
}
},
cursor:{
show: true,
zoom:true
},
// Series options are specified as an array of objects, one object
// for each series.
series:[
{
// Don't show a line, just show markers.
// Make the markers 7 pixels with an 'x' style
showLine:false,
markerOptions: { size: 7, style:"x" }
}
]
}
);
};

update_chart();

$(document).on(‘ajax:complete’, ‘form.as_form’, function(event) {
update_chart();
});

});

ActiveScaffold render :super

Leave a comment

You all may know that there is a quite flexible hierarchy for activescaffold s templates and partials.
If you would like to override one in general for your application copy and change it in app/views/active_scaffold_overrides/.
If you would like to override one just for one specific controller copy and change it in app/views/controller_name/.

In addition to do a full override you may also call parent s view eg. to wrap parent template/view or to change some locals. I will show you how to do that in this post.

Just a simple render :super call in your overwritten template/partial is all you need to activate this feature.

<%= render :super %>

If you would like to change a local variable you have to do the following and it depends on your activescaffold version:

:super with locals for ActiveScaffold 3.0

<%= render :super, :locals => {:headline => 'My _base_form headline'} %>

:super with locals for ActiveScaffold 3.1 and 3.2

<%= render :partial => :super, :locals => {:headline => 'My _base_form headline'} %>

ActiveScaffold Asset Pipeline Comparison

5 Comments

Today I would like to compare a activescaffold rails 3.0 controller index action waterfall chart with one of a rails 3.1 controller.
You will see a big difference in these charts because of the asset pipeline feature. Asset pipeline is merging your js and css assets into one big file which improves your webperformance because of reduced http requests.
In addition I m using css data-uri feature for background images. Please note that ie6 and ie7 do not support data-uris.

Rails 3.0 waterfall

Rails 3.1 waterfall

ActiveScaffold Unobtrusive Javascript and TinyMCE

2 Comments

My last post covered the topic how ActiveScaffold and Unobtrusive Javascript may fit together. This time I would like to give you an example.
It s Activescaffold’s TinyMCE Bridge. It s a perfect example, cause it s a pure javascript feature.
Let’s take a look at the bridge file using obtrusive javascript:

Loading tinymce editor

Obtrusive Javascript

def active_scaffold_input_text_editor(column, options)
    options[:class] = "#{options[:class]} mceEditor #{column.options[:class]}".strip
    html = []
    html << send(override_input(:textarea), column, options)
    html << javascript_tag("tinyMCE.execCommand('mceAddControl', false, '#{options[:id]}');") if request.xhr?
    html.join "\n"
end

We use an activescaffold input override to add javascript code to our textareas.

Unobtrusive Javascript

$('form.as_form').live('as:form_loaded', function(event) {
  var as_form = $(this).closest("form");
  as_form.find('textarea.as_mceEditor').each(function(index, elem) {
    tinyMCE.execCommand('mceAddControl', false, $(elem).attr('id'));
  });
  return true;
});

A listener to activescaffold form_load event, finding all textareas and adding tinyMCE control.

Submitting tinymce editor

Obtrusive Javascript

def onsubmit
    if ActiveScaffold.js_framework == :jquery
       submit_js = 'tinyMCE.triggerSave();$(\'textarea.mceEditor\').each(function(index, elem) { tinyMCE.execCommand(\'mceRemoveControl\', false, $(elem).attr(\'id\')); });' if using_tiny_mce?
    else
       submit_js = 'tinyMCE.triggerSave();this.select(\'textarea.mceEditor\').each(function(elem) { tinyMCE.execCommand(\'mceRemoveControl\', false, elem.id); });' if using_tiny_mce?
    end
    [super, submit_js].compact.join ';'
end

We use form submit method override to add javascript code, which will call tinyMCE.triggerSave method.

Unobtrusive Javascript

$('form.as_form').live('as:form_submit', function(event) {
  var as_form = $(this).closest("form");
  if (as_form.has('textarea.as_mceEditor').length > 0) {
    tinyMCE.triggerSave();
  }
  return true;
});

A listener to activescaffold form_submit event, finding all textareas using tinyMCE and calling triggerSave.

Removing tinymce editor

Obtrusive Javascript

def active_scaffold_includes(*args)
        if ActiveScaffold.js_framework == :jquery
          tiny_mce_js = javascript_tag(%|
var action_link_close = ActiveScaffold.ActionLink.Abstract.prototype.close;
ActiveScaffold.ActionLink.Abstract.prototype.close = function() {
$(this.adapter).find('textarea.mceEditor').each(function(index, elem) {
tinyMCE.execCommand('mceRemoveControl', false, $(elem).attr('id'));
});
action_link_close.apply(this);
};
|) if using_tiny_mce?
        else
        ....
        end
        super(*args) + (include_tiny_mce_if_needed || '') + (tiny_mce_js || '')
      end

Ok, we add a javascript code snippet to activescaffold includes in case using_tiny_mce? returns true. Javascript code will link into action link.close action management and will remove our tiny_mce_editor. To be honest I do not like that solution at all. :-)

Unobtrusive Version

$('form.as_form').live('as:form_unloaded', function(event) {
  var as_form = $(this).closest("form");
  as_form.find('textarea.as_mceEditor').each(function(index, elem) {
    tinyMCE.execCommand('mceRemoveControl', false, $(elem).attr('id'));
  });
  return true;
});

A listener to activescaffold form_unload event, finding all textareas and removing tinyMCE control.

Summary

Did we achieve our goals?
We ve separated javascript code from ruby code. which improves code quality and maintainability. You do not have to be an activescaffold expert anymore to add javascript functionality to forms, form_columns, list_columns. You just need to know javascript.

Hope that helps.

ActiveScaffold and Unobtrusive Javascript

Leave a comment

Rails 3.0 started using unobtrusive javascript. However, what does that actually mean for activescaffold? Well, basically it means that there should nt be any javascript code in our partials. Looks easy at the first glance, however, if you start actually to implement it..
Big advances of unobtrusive javascript are:

  • application works without javascript
  • html code seperated from javascript code
  • html id attribute is nt needed anymore for many operations

I ve mentioned at the beginning that going unobtrusive is nt that easy as it seems. The big issues you have are:

  • How to cleanly separate javascript code?
  • How may application work if javascript is disabled?
  • It s easy to manage click events, unobtrusively, but how to manage load events for ajax calls?

In this post I will focus on the last bullet point. It took a while until I was able to manage that issue.
Unobtrusive javascript needs a trigger event to add the javascript functionality. For example when you click a button. However, if you would like to add javascript functionality on load you are in kind of trouble for ajax applications, because load events of browsers do only fire if the whole page is loaded and not if snippets of html code are changed or added during an ajax call.

I ve solved that issue at least for activescaffold as follows.

ActiveScaffold will trigger the following events in case of page load and ajax load:

  • as:list_row_loaded
  • as:form_loaded
  • as:form_element_loaded

ActiveScaffold will trigger the following events in case of page unload and ajax unload:

  • as:list_row_unloaded
  • as:form_unloaded
  • as:form_element_unloaded

A simple use case would be the following: list columns may be configured for inplace editing, which is a pure javascript feature including the need to add it to the specified columns during as:list_row_load event:

$('tr.record').live('as:list_row_loaded', function(event) {
  $(this).closest("tr").find('td > span.in_place_editor_field').each(function(index) {
    ActiveScaffold.create_inplace_editor($(this));
  });
  return true;
});

In my next post I will show you how I ve migrated the tiny_mce bridge to unobtrusive javascript.

Hope you will benefit from this new javascript events, cause it will make the step to unobtrusive javascript a lot easier using activescaffold.

ActiveScaffold per Request Configuration for ActionColumns

7 Comments

If you take a look at Activescaffold per Request Configuration you will learn that you have to create a before_filter to be able to change column set per request.
Well, that does nt feel right, before_filters should be used for aspect oriented programming tasks such as authentication, logging,..

However, it was quite complicated to do it another way with Activescaffold.

I ve added a new feature to my fork which allows you to change column set configuration for a specific action without before_filters.

It s actually really easy, every action has a new method _columns, which you may override in your controller.

Let me give you some easy examples:

def update_columns
  columns = super
  if @record.id == 85
    columns.select {|column| column.name != :last_name}
  else
    columns
  end
end
def field_search_columns
  columns = super
  if sunny_weather
    columns.select {|column| column.name != :rain}
end

Wish you a great weekend.

ActiveScaffold and Rails 3.1

27 Comments

Today I would like to give you a short guide about how you may get ActiveScaffold up and running with Rails 3.1. Please be aware that ActiveScaffold is nt fully ported to Rails 3.1, so this guide is for early adopters who wanna try it out or help finishing development work.

I assume that you ve got Rails 3.1/3.2 already installed on your computer.

1. rails new as_rails31
2. please add below the line gem ‘jquery_rails’ in your gem file following code:
Official Gems:

gem 'render_component_vho'
gem 'active_scaffold_vho'

Github Gems:

gem 'render_component_vho', :git => 'git://github.com/vhochstein/render_component.git'
gem 'active_scaffold_vho', :git => 'git://github.com/vhochstein/active_scaffold.git'

3. bundle install
4. bundle exec rake db:create
5. rails g active_scaffold Team name:string position:integer
6. bundle exec rake db:migrate
7. Edit file /app/assets/javascripts/application.js

//= require jquery
//= require jquery-ui
//= require jquery_ujs
//= require active_scaffold
//= require_tree .

8. Edit file /app/assets/stylesheets/application.css

 *= require active_scaffold
 *= require_self
 *= require_tree . 

Hope you will enjoy.

Older Entries

Follow

Get every new post delivered to your Inbox.