Feed on
Posts
Comments
  • “i got what i want”.count “i” #=> 2
  • “i got what i want”.delete “i” #=> ” got what want”
  • “hello”.gsub(/[aeiou]/, ‘*’) #=> “h*ll*”
  • “hello”.sub(/[aeiou]/, ‘*’) #=> “h*llo”
  • “hello”.tr(’aeiou’, ‘*’) #=> “h*ll*”
  • “hello”.index(’e') #=> 1
  • “hello”.rindex(’l') #=> 3(last occurrence)
  • “abcd”.insert(3, ‘X’) #=> “abcXd”
  • ‘cat’.to_sym #=> :cat
  • “hello”.ljust(20) #=> “hello “
  • “hello”.ljust(20, ‘1234′) #=> “hello123412341234123″
  • “hello”.rjust(20, ‘1234′) #=> “123412341234123hello”
  • ” hello “.rstrip #=> ” hello”
  • ” hello “.lstrip #=> “hello “
  • ” hello “.strip #=> “hello”
  • a = “cruel world”
  • a.scan(/\w+/) #=> ["cruel", "world"]
  • a.scan(/…/) #=> ["cru", "el ", "wor"]
  • a.scan(/(…)/) #=> [["cru"], ["el "], ["wor"]]
  • a.scan(/(..)(..)/) #=> [["cr", "ue"], ["l ", "wo"]]
  • “1,2,,3,4,,”.split(’,') #=> ["1", "2", "", "3", "4"]
  • “putters shoot balls”.squeeze(”m-z”) #=> “puters shot balls”
  • “Finally, something useful!”.at(6) #=> “y”
  • “Chris the Person”.from(6) #=> “the Person”
  • “Chris the Person”.to(4) #=> “Chris”
  • “Christmas Time”.first #=> “C”
  • “Christmas Time”.first(5) #=> “Chris”
  • “Christmas Time”.last #=> “e”
  • “Christmas Time”.last(4) #=> “Time”
  • “Snow”.each_char { |i| print i.upcase } #=>SNOW
  • “Peanut Butter”.starts_with? ‘Peanut’ #=> true
  • “Peanut Butter”.ends_with? ‘Nutter’ #=> false
  • “1985-03-13″.to_time #=> Wed Mar 13 00:00:00 UTC 1985
  • “1985-03-13″.to_date #=> #
  • “stressed”.reverse #=> “desserts”
  • “Hello”.swapcase #=> “hELLO”
  • “hEllO”.upcase #=> “HELLO”
  • “reindeer”.pluralize #=> “reindeers”
  • “elves”.singularize #=> “elf”
  • “christmas_carol”.camelize #=> “ChristmasCarol”
  • “christmas_carol”.camelize(:lower) #=> “christmasCarol”
  • “holiday_cheer”.titleize #=> “Holiday Cheer”
  • “AdventCalendar-2006″.underscore #=> “advent_calendar_2006″
  • “santa_Claus”.dasherize #=> “santa-Claus”
  • “Holiday::December::Christmas”.demodulize #=> “Christmas”
  • “SnowStorm”.tableize #=> “snow_storms”
  • “snow_storms”.classify #=> “SnowStorm”
  • “present_id”.humanize #=> “Present”
  • “Present”.foreign_key #=> “present_id”
  • “Cheer”.constantize #=> NameError: uninitialized constant Cheer
  • “Christmas”.constantize #=> Christmas

Ferret Upgrade

These are the steps I have followed for ferret gem upgrade.

Step 1> Upgrade ferret gem  to new version 0.11.6
>>sudo gem update ferret

Step 2> Run setup.rb in ferret-0.11.6
>>ruby /usr/lib/ruby/gems/ferret-0.11.6/setup.rb

Step 3> Update acts_as_ferret plugin in application
>> script/plugin install svn://projects.jkraemer.net/acts_as_ferret/tags/stable/acts_as_ferret –force

Step 4> Add below lines in ferret_server.yml for testing
development:
host: localhost
port: 9010

Step 5> Delete index folder

Step 6> Do changes in file /vendor/plugins/acts_as_ferret/lib/server_manager.rb
- Comment the line, require(File.join(File.dirname(ENV['_']), ‘../config/environment’))
- Uncomment the line, require(File.join(File.dirname(__FILE__), ‘../../../../config/environment’))

Step 7> Restart System

Step 8> Run ferret server
>>ruby script/ferret_server start

Step 9> Restart Apache and webrick

Step 10> Test the search functionality

When i am running my server I got this error

anand-muranals-macbook:Trunk anandmuranal$ ruby script/server
=> Booting Mongrel (use ’script/server webrick’ to force WEBrick)
=> Rails application starting on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
** Ruby version is up-to-date; cgi_multipart_eof_fix was not loaded
** Starting Mongrel listening at 0.0.0.0:3000
** Starting Rails with development environment…
Exiting
/Users/anandmuranal/Projects/Trunk/vendor/rails/railties/lib/commands/servers/mongrel.rb:15: warning: already initialized constant OPTIONS
/Users/anandmuranal/Projects/Trunk/vendor/rails/railties/lib/commands/servers/mongrel.rb:18: undefined method `options’ for []:Array (NoMethodError)
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/custom_require.rb:32:in `gem_original_require’
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/custom_require.rb:32:in `require’
from /Users/anandmuranal/Projects/Trunk/vendor/rails/activesupport/lib/active_support/dependencies.rb:495:in `require’
from /Users/anandmuranal/Projects/Trunk/vendor/rails/activesupport/lib/active_support/dependencies.rb:342:in `new_constants_in’
from /Users/anandmuranal/Projects/Trunk/vendor/rails/activesupport/lib/active_support/dependencies.rb:495:in `require’
from /Users/anandmuranal/Projects/Trunk/vendor/rails/railties/lib/commands/server.rb:39
from script/server:3:in `require’
from script/server:3
anand-muranals-macbook:Trunk anandmuranal$

This error will come because you are missing some gem which is required in your application

How to know that, which gem is missing?

Run server by this command

ruby script/server webrick

It will tell you which gem that it fails to load

After this I came to know that ruby-debug is missing

The solution for me was installing the ruby-debug gem - sudo gem install ruby-debug

Now it’s working

bit about Flex

Ø  IIntroduction

1>   Flex Framework

·          Drag manger

·          Event manager

·          Layout manger

·          Focus manager

·          Cursor manager

 

2>   Action script

3>   Mxml

4>   Css

5>   Swc

 

Ø  Flex – swf

 

Ø  Container

 

Ø  Component

 

Ø  Display layout

 

Ø  Mx:Application  layout

·          Absolute

·          Horizontal

·          Vertical

 

Ø  Application start by

·          Pure action script

·          Mxml and action script

 

Data Binding - Data binding is the process of tying the data in one object to another object. It provides a convenient way to pass data around in an application.

Ex : <mx:Slider id=”mySlider”/> <mx:Text text=”{mySlider.value}”/>

 

Data Models  - The data model feature lets you store data in client-side objects.

            Mx:xml

            Mx:model

Data Validation - The data validation feature lets you ensure that data meets specific criteria before the application uses the data.

Using the CreditCardValidator class

Using the CurrencyValidator class

Using the DateValidator class

Using the EmailValidator class

Using the NumberValidator class

Using the PhoneNumberValidator class

Using the RegExpValidator class

Using the SocialSecurityValidator class

Using the StringValidator class

Using the ZipCodeValidator class

 

Ex: <mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml”>     <mx:TextInput id=”input” text=”enter zip” width=”80″/>       <mx:Model id=”zipModel”>         <root>             <zip>{input.text}</zip>         </root>         </mx:Model>       <mx:ZipCodeValidator source=”{zipModel}” property=”zip”         listener=”{input}” trigger=”{input}”/> </mx:Application>

 

Data formatting - The data formatting feature lets you change the format of data before displaying it in a user interface control.

Ex : <mx:DateFormatter id=”StandardDateFormat” formatString=”MM/DD/YYYY”/>   Behaviors - Adobe Flex behaviors let you add animation and motion to your application in response to user or programmatic action

<mx:Parallel id=”BlurMoveShow” target=”{myLabel}”>

        <mx:Blur id=”numbersBlur”

            blurYFrom=”10.0″ blurYTo=”0.0″

            blurXFrom=”10.0″ blurXTo=”0.0″

            duration=”2000″/>

        <mx:Move id=”numbersMove” yBy=”20″ duration=”2000″/>   

    </mx:Parallel>

 

Event Listener

View states and Transitions - you can use view states to create a user interface that changes its appearance based on the task the user is performing

 

Install gem aws s3
gem install aws-s3

Before you can do anything, you must establish a connection using Base.establish_connection!. A basic connection would look something like this:

AWS::S3::Base.establish_connection!(:access_key_id => ‘abc’,
:secret_access_key => ‘123′
)

Buckets are containers for objects (the files you store on S3). To create a new bucket you just specify its name.

AWS::S3::Bucket.create(’bucket_name’)

Picture upload view

<% form_tag ({:action => ‘create’},{:multipart => true}) do %>
<table>
<tr>
<td>Image </td>
<td> <%= file_field_tag “event_picture” %></td>
</tr>
</table>
<%= submit_tag “Create” %>
<% end %>

Controller
include require ‘aws/s3′ in controller

def create
filename = @params['event_picture'].original_filename.gsub(/[^a-zA-Z0-9.]/,’_')
data = @params['event_picture'].read
AWS::S3::Base.establish_connection!(:access_key_id => ‘123′,
:secret_access_key => ‘abc’)
AWS::S3::S3Object.store(filename,
data,
‘bucket_name’,
:content_type => ‘image/jpg’)
end

even you can change grants for image

policy = AWS::S3::S3Object.acl(filename, ‘bucket_name’)
policy.grants << AWS::S3::ACL::Grant.grant(:public_read)
policy.grants << AWS::S3::ACL::Grant.grant(:public_read_acp)
AWS::S3::S3Object.acl(filename, ‘bucket_name’, policy)

More info click 

suppose you want to convert datetime in client side(browser) time zone and display it.
example take events, Events have date so that event date first you have to store it in database as GMT timezone
then write javascript function for onload event like this

function events()
{
var currentDate = new Date();
var offset = currentDate.getTimezoneOffset().toString();
new Ajax.Updater(’events’, ‘/events/load_events?offset=’ + offset, {asynchronous:true, evalScripts:true}); return false;
}

The events.rhtml will be like this

<h1>Events</h1>
<div id=”events”></div>

In third line of javascript I am making an ajax call with updating “events” div tag.
This ajax will call the action “load_events” in controller “events”

events_controller.rb

def load_events
@events = Event.find(:all)
@offset = params[:offset].to_i
end

In view “load_evevnts.rhtml” calculate date with offset

<ul>
<% @events.each do |e| %>
<li><%= e.name %> on <%= (e.date - offset) %></li>
<% end %>
</ul>

You can format Date field by using strftime function

example :

Time.now()
=> Wed Dec 12 15:48:59 +0530 2007

Time.now().strftime(”%d/%m/%y %H:%M”)
=> “12/12/07 15:50″

Here’s the (shortened) table for strftime.

%a  weekday name.
%A  weekday name (full).
%b  month name.
%B  month name (full).
%c  date and time (locale)
%d  day of month [01,31].
%H  hour [00,23].
%I  hour [01,12].
%j  day of year [001,366].
%m  month [01,12].
%M  minute [00,59].
%p  AM or PM
%S  Second [00,61]
%U  week of year (Sunday)[00,53].
w  weekday [0(Sunday),6].
W  week of year (Monday)[00,53].
x  date (locale).
%X  time (locale).
%y  year [00,99].
%Y  year [2000].
%Z  timezone name.

suppose u have html page like this

<html>
<body>
<p>Name : Anand m Muranal</p>
<p>city : bangalore</p>
<p>state: karnataka</p>
<p>country : india</p>
</body>
</html>

now you want to some link which will go to city
then add some id to <p> tag of city and same id use for link, like this

<html>
<body>
<p>Name : Anand m Muranal</p>
<p id = “city”>city : bangalore</p>
<p>state: karnataka</p>
<p>country : india</p>
<a href=”#city”>Go to City</a>
</body>
</html>

Time zone Conversion

    The most common time zone conversions are the conversion of system local time to UTC, and the conversion of UTC to local time by “Time.gmtime” method and “Time.localtime” method respectively. These conversions are easy for both Time and DateTime objects.

 

def convert_zone(to_zone)
    original_zone = ENV["TZ"]
    utc_time = dup.gmtime
    ENV["TZ"] = to_zone
    to_zone_time = utc_time.localtime
    ENV["TZ"] = original_zone
    return to_zone_time

end


Add this function in application controller and call this by passing time zone parameter. This will return time in new timezone(which u send as parameter).

In this function we are converting time to UTC and changing local timezone to parameter timezone and then converting UTC time to local.

finally reassigning local timezone to original timezone by setting ENV['tz'].

Test it

t = Time.now                             # => Sun Sep 09 01:46:40 UTC 2001

t.convert_zone(”Asia/Calcutta”)   # => Sun Sep 09 07:16:40 IST 2001


Suppose you have table like

User Table with fields id(auto increment) and name

address table with field id(auto increment), address, user_id(foreign key)

when u inserted one row in user table then u want the last inserted id value in user table to insert it into address table in the field user_id for that corresponding user address entry

use mysql ‘”last_insert_id()” function for finding last inserted auto id

example:

insert into user (name) values (”Anand”)

insert into address (address,user_id) values (”Bangalore”,last_insert_id())

user table

id     name

1     Anand

Address Table

id     address     user_id

1     Bangalore     1

Older Posts »