Categories
static_site_generators

Brunch, the Static site generator

In most web apps, there are two types of pages. One are those just for visitors who are not yet our customers and other belongs to APP which provides the core functionality of the service.

In most scenarios all these non service based content pages are combined into app, hence overloading the app with irrelevant code resulting in slow response time and necessity to update and deploy the app for minor text changes.

Categories
ruby

Reading & Writing DBF files in ruby

DBFs are a set of database file formats similar to sqlite, except that each file will have only one table. The support for reading & writing dbase file formats in ruby is pretty rudimentary.

The following are the gems that can be used to read & write dbase files.

1. SHP

The file format it supports is xbase. It supports creation of columns of type string, integer and float only. The type codes for columns types are
0 -> string, 1 -> integer and 2 -> float respectively. Even though date is a valid xbase column type, it is not supported. Simple usage is

Add

gem shp

to you Gemfile.

Then the code to read the data from dbase is

#Open the file to read
dbf = SHP::DBF.open('path_to/file.dbf', 'rb+')
data = [] #variable to collect read data
dbf.get_record_count.times do |record_no|
  data[record_no] ||= []
  dbf.get_field_count.times do |column_no|
    # call appropriate function according to field type
    data[record_no][column_no] = case dbf.get_field_info(column_no)[:type]
                                  when 0
                                    dbf.read_string_attribute(record_no, column_no)
                                  when 1
                                    dbf.read_integer_attribute(record_no, column_no)
                                  when 2
                                    dbf.read_double_attribute(record_no, column_no)
                                  end
  end
end

puts data

While reading is kind of straight forward, writing to the dbf is a complicated affair. You have to create the file first then add field specifications and then add data.

require "shp"
#Open the file to write
dbf = SHP::DBF.create('file.dbf')

#declare type of columns
fields = [
            {name: 'name', type: 0, width: 25, decimals: 0}, 
            {name: 'age', type: 1, width: 19, decimals: 0}
        ]
fields.each do |field_info|
  dbf.add_field(field_info[:name], field_info[:type], field_info[:width], field_info[:decimals])
end

data = [['john', 28], ['mike', 21], ['jack', 20]]
data.each_with_index do |details, record_no|
 details.each_with_index do |value, index|
    case fields[index][:type]
    when 0
      dbf.write_string_attribute(record_no, index,  value)
    when 1
      dbf.write_integer_attribute(record_no, index, value)
    end
  end
end
#close the file after writing
dbf.close

2. DBF
This gem can only be used for reading from dbf files. One cannot use it to create dbf files.
To use as usual add to you Gemfile

gem 'dbf'

and

data = File.open('widgets.dbf')
widgets = DBF::Table.new(data)
#returns all file data into rows as an array of hashes with field names as keys
rows = widgets.map{|widget| widget.attributes }

3. Rbase

Rbase lacks documentation. But if you are used to wading through code in the wild, you will quickly get a hang of it and start writing & reading dbase files using this. It definitely provides a rich interface to reading
To read from a dbase file.

require "rbase"
require "date"
dbf = RBase::Table.open('file') #notice, without .dbf extension
records = []
dbf.each do |record|
  attr_hash = {}
  dbf.columns.each do |column|
    attribute_name = column.name
    attr_hash[attribute_name] = record.send(attribute_name)
  end
  records << attr_hash
end
Categories
javascript

Sticky Footer Bar using jquery when scrolling

The zurb foundation has a sticky top bar. But they don’t have a sticky footer / lower bar. This is an attempt to implement the sticky footer bar similar to that found in cnn.com

Let the footer id be

sticky-footer

. When we scroll up we check for the current position of the scroll of the window and add the sticky css class to the footer. When the scroll reaches the original postion of the footer we restore the original positioning.
The css required for fixed footer is

.fixed_footer{
  position: fixed;
  bottom: 0;
  width: 100%;
}

The javascript that adds and removes the fixed class is

//save the existing postion of the footer
$footer = $('#sticky-footer');
$win = $(window);
var ipos = $footer.offset().top;
var wpos, space;

function h(e){
      wpos = $win.scrollTop();
      space = $win.height() - $footer.height()*2;
      if (wpos + space < ipos) {
          $footer.addClass('fixed_footer');
      } else {
          $footer.removeClass('fixed_footer');
      }
}
// this triggers the repositioning of the bar on all relevant events
$(window).ready(h).resize(h).scroll(h);

JSfiddle demo

Categories
ruby on rails

Fetching value of hidden input field in capybara

There can be many instances in testing with capybara where you might need to interact with hidden fields. By default capybara’s

find_field

selector ignores hidden fields.
To get the value of the hidden field you can use

page.all
page.all("input['name=you_input_name']", :visible => false).first.value
# you have to use first as it returns and array of element matching the query criteria

To set the value of the hidden field you can use

page.all("input['name=you_input_name']", :visible => false).first.set(value_to_set)
Categories
nodejs

Reading from and writing to files in node.js

NodeJS is an awesome platform to build applications in javascript which can run on the server.
It allows you to read n write to files asynchronously and synchronously

Writing Data to files

The easiest way would be write synchronously (i.e. wait till the writing operating is finished)

var fs = require('fs');
fs.writeFileSync('/path/to/some_text.txt', 'some text');

But the preferable way of writing to files will be asynchronous in context of web apps.

var fs = require('fs');
fs.writeFile("/path/to/some_text.txt", "test data!", function(err) {
    if(err) {
        console.log(err);
    } else {
        console.log("file has been saved successfully");
    }
});

In this case the program will continue to execute next instruction without waiting for the file write to complete. Once the file writing is completed, the third parameter (closure ) is executed. Above method overwrite the current file. So if you want to append the data, use

Categories
ruby on rails

Customizing Mailboxer mailer views

To copy the mailboxer mailer views to your rails app run

rails g mailboxer:views

This will generate two folders, message_mailer and notification_mailer with html & text views for messages, notification and message replies respectively.

Next create a modify the initializer of mailboxer to include the following config

Mailboxer.setup do |config|
  #Enables or disables email sending for Notifications and Messages
  config.uses_emails = true
  #Configures the default `from` address for the email sent for Messages and Notifications of Mailboxer
  config.default_from = "admin@yoursite.com"
end

Add the following method to your messageable model

  #Returning the email address of the model if an email should be sent for this object (Message or Notification).
  #If no mail has to be sent, return nil.
  def mailboxer_email(object)
  #Check if an email should be sent for that object
  #if true
    return "define_email@on_your.model"
  #if false
  #return nil
  end

To change the title of you mail messages

open config/locales/en.yml and you will see the following line belonging to each mail you can the below line to suit to your needs

en:
  mailboxer:
    message_mailer:
      subject_new: "Mailboxer new message: %{subject}"
      subject_reply: "Mailboxer new reply: %{subject}"
    notification_mailer:
      subject: "Mailboxer new notification: %{subject}"
Categories
ruby ruby on rails

Adding TinyMce editor to Rails Admin

RailsAdmin is a Rails engine that provides an easy-to-use interface for managing your data. Rails admin is like bootstrap admin interface for your web app / site. To add tinymce editor to all textareas in rails_admin first add the tinymce-rails gem to your Gemfile and run bundle install.

Gemfile

gem 'tinymce-rails', :git => 'git://github.com/spohlenz/tinymce-rails.git', :branch => 'tinymce-4'

Now got to app/assests/javascripts/rails_admin folder and include the tinymce javascript libraries to rails_admin.js.erb file like this

//= require 'tinymce-jquery'

Now create a javascript file called tinymce.js in app/assets/javascripts/rails_admin folder and add the following code to invoke tinymce on all textareas

function tinymce_load(){
  tinymce.init({
    selector: "textarea",
    plugins: [
     "advlist autolink lists link image charmap print preview anchor",
     "searchreplace visualblocks code fullscreen autoresize",
     "insertdatetime media table contextmenu paste"
    ],
    menu : "core",
    toolbar: "undo redo | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link"
  });
}
$(window).load(tinymce_load());
$(document).on('pjax:complete', tinymce_load );

A note on pjax line. RailsAdmin uses pjax for better user experience so we have to trigger the tinymce_load function when ever pjax is called so that the new textareas are also tinymced!

then include this file in rails_admin.js.erb file like

//= require 'rails_admin/tinymce'

Now restart your server and you have tinymce loading on all textareas. For more customization options of tinymce please refer their website.

 

Categories
ruby ruby on rails

A treatise on mailboxer ruby gem

Mailbox Gem

Mailboxer gem adds messaging capability to your models.By far of all messaging gems we have found this one easy to implement / add to your models with good documentation.

Mailboxer Installation

In you rails application add

gem "mailboxer", "~> 0.9.0"

to your Gemfile and run bundle install to install it.

Now go to rails application directory and run to generate the necessary migrations and then migrate the changes to your database

rails g mailboxer:install
rake db:migrate

Configuring Maiboxer

In rails you can create an intializer called mailboxer.rb in folder /config/intializer and modify the default behaviour of mailboxer. An example intializer. In our setup we are not interested in user emails. so we have just disabled it. Mailboxer automatically generates a initializer for you can go and change the default settings.

Mailboxer.setup do |config|

  #Configures if you applications uses or no the email sending for Notifications and Messages
  config.uses_emails = false

  #Configures the default from for the email sent for Messages and Notifications of Mailboxer
  config.default_from = "no-reply@mailboxer.com"

  #Configures the methods needed by mailboxer
  # These methods must be implemented in the model which will be using mailboxer
  config.email_method = :email # This method is needed only if you are going to send an email for each converstion / replies
  config.name_method = :name # This method is needed if you want to user mailboxer

  #Configures if you use or not a search engine and wich one are you using
  #Supported enignes: [:solr,:sphinx]
  config.search_enabled = false
  config.search_engine = :solr
end

Preparing the Model

In your user model add acts_as_messageable and implement the method name as shown below

class User < ActiveRecord::Base
  attr_accessible :email, :first_name, :last_name
  acts_as_messageable

  # Returns the name of the user
  def name
   return "#{first_name} #{last_name}"
  end
end

Basic Messaging

In mailboxer when an user send message to another user, a conversation is started. So there will be a notification is created with the content of the message and a receipt of notification is add to sent box of the sending user and a receipt of notification is added to the inbox of receiving user.

mailboxer flow (1)

To send a message to user2 from user1

user1.send_message(user2, body_of_the_message, subject_of_the_message)

#sending a message

To send message to multiple users use (just pass and array of recipients to send_message function.

user1.send_message([user2, user3, user4], body_of_the_message, subject_of_the_message)

To reply to the message

#message reply
user2.reply_to_conversation(conversation, "Reply body")

#Reply to all in the conversation (if the conversation involves more than two users )
user2.reply_to_all(receipt, "Reply body")

#To reply to the message sender
user2.reply_to_sender(receipt, "Reply body")

Retrieve all messages of the user

#user1 wants to retrieve all his conversations
user1.mailbox.conversations

#user1 wants to retrieve his inbox
user1.mailbox.inbox

#user1 wants to get unread messages in inbox
user1.mailbox.inbox(:unread => true)

#user1 wants to get all the read messages in inbox
user1.mailbox.inbox - user1.mailbox.inbox(:unread => true)

#user1 wants to retrieve his sent conversations
user1.mailbox.sentbox

#user1 wants to retrieve his trashed conversations
user1.mailbox.trash

To read the contents of a conversation user get the receipts of the message for him and reads the messages. The following snippet gets the messages in a conversation in reverse chronological order.

#user gets the last conversation (chronologically, the first in the inbox)
conversation = user1.mailbox.inbox.first

#user gets it receipts chronologically ordered.
receipts = conversation.receipts_for user1

#using the receipts (i.e. in the view)
receipts.each do |receipt|
  message = receipt.message
  read = receipt.is_unread?
end

Misc stuff

#To get the originator of the conversation
conversation.originator

#To get all participants of the conversation
conversation.particpants

#To get the first messsage of the conversation
conversation.original_message

#To get no of messages in the conversation
conversation.count_messages

#to mark a conversation as read by the participant (example user2)
user2.mark_as_read(conversation)

To change the views of email messages

#run this command
rails g mailboxer:views

the views are added to your app/views folders so you can edit them.

Thats all for now folks. If you need more info just post in the comments i will try to answer

Update: Follow up tutorial on how to customize mailboxer views

References

  1. https://github.com/ging/mailboxer
  2. http://www.rubydoc.info/github/ging/mailboxer/frames
Categories
ruby on rails

Calling View helper methods from Controller / Model in Rails 3.* and Rails 2.*

To access view helper methods from controller / models in rails 3 you have to use view_context method. Example

view_context.link_to "This is my link", "/"

In rails 2 you have to user @template instance variable as shown below

@template.link_to "This is my link", "/"

Just a note that you should avoid calling these functions within the controllers to follow mvc pattern conventions.

Categories
php

How to Install Php Extension

The easiest way to install php extension is using pecl.

To install you have to run

pecl install extension_name

But if you have the sources of the php extension then.

cd extension_name_folder
phpize
./configure
make
make install

if you have php installed in another location. Lets assume php is installed in /opt/php
To install the extension you have to do is first download the extension and then unzip it and run the phpize and make and make install. Example commands to run

pecl download extenstion_name # you will see a .tgz / .zip / .tar.gz file
unzip  extension_name.zip # unzip  / untar it using tar xvfz extension_name.tar.gz
cd extension_name_folder
export PHP_PREFIX="/opt/php"
$PHP_PREFIX/bin/phpize
./configure --with-php-config=$PHP_PREFIX/bin/php-config
make
make install

Then to enable you have to add in your php.ini file

extension=extension_name.so