Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS 

rake tasks to sync project hosted on freeonrails

// rake tasks to sync project hosted on freeonrails

require File.dirname(__FILE__) + "/scp_wrapper"

desc "pushes the app files onto freeonrails"
task :update_freeonrails => :environment do |t|
  
  scp_wrapper = ScpWrapper.new
  scp_wrapper.update_code
  scp_wrapper.update_db
  scp_wrapper.update_javascript
  scp_wrapper.update_css
  scp_wrapper.update_tests
#  scp_wrapper.images
end

// ha .. moved over to rsync last moment
class ScpWrapper
  
  def update_code
    sync "app"
  end
  
  def update_db
    sync "db/migrate", "db"
  end
  
  def update_javascript
    sync "public/javascripts", "public"
  end
  
  def update_css
    sync "public/stylesheets", "public"
  end
  
  def update_tests
    sync "test"
  end
  
  def images
    sync "public/images", "public"
  end

  private 
  
  def sync(source, dest = "")
    system "rsync -avz #{RAILS_ROOT}/#{source} biketw@biketowork.info:/home/biketw/btw/#{dest}"  
    puts "#{source} synched"
  end
  
end

Simple enum creation

// simple Enum creation

module Kernel
  # simple (sequential) enumerated values
  def enum(*syms)
    syms.each { |s| const_set(s, s.to_s) }
    const_set(:DEFAULT, syms.first) unless syms.nil?
  end
end

//and the usage

require 'kernel'



module Constants

  module Gradient

    enum :DOWNSLOPE, :LEVEL, :UPSLOPE

  end

  

  module TreeCover

    enum :GOOD, :BAD, :OK

  end

  

  module TrafficDensity

    enum :LOW, :MEDIUM, :HIGH

  end

end

Building drop down boxes using enum generated Constants

Building drop down boxes using enum generated Constants


require 'constants'

module MapHelper
  LOCAL_KEY = 
  FREE_ON_RAILS_KEY = 
  
  def key
    case `hostname`.chomp
    when 'localhost', 'rohan'
      LOCAL_KEY
    else
      FREE_ON_RAILS_KEY 
    end
  end
  
  def tree_cover
    build_options Constants::TreeCover
  end
  
  def gradient
    build_options Constants::Gradient
  end
  
  def traffic_density
    build_options Constants::TrafficDensity
  end
  
  def default(method)
    eval "Constants::#{method}::DEFAULT"
  end
  
  private
  
  def build_options(sym)
    sym.constants.inject("") {|str, value| str + wrap(value) }
  end
  
  def wrap(option)
    "<option value='#{option}'> #{option.downcase.capitalize} </option>"
  end
end


// and the tests for this
require File.dirname(__FILE__) + '/../test_helper'

class MapHelperTest < Test::Unit::TestCase
  include MapHelper
  
  def test_options_for_combo_box_are_built_correctly
    assert_tree_cover :GOOD
    assert_gradient :DOWNSLOPE
    assert_traffic_density :LOW
  end
  
  def test_defaulting
    assert_default :TreeCover, :GOOD
    assert_default :Gradient, :DOWNSLOPE
    assert_default :TrafficDensity, :LOW
  end
  
  def assert_default(subject, const)
    assert_equal const, default(subject)
  end
  
  def assert_tree_cover(const)
    const = const.to_s
    assert tree_cover.include?(option_string(const))
  end
  
  def assert_gradient(const)
    const = const.to_s
    assert gradient.include?(option_string(const))
  end
  
  def assert_traffic_density(const)
    const = const.to_s
    assert traffic_density.include?(option_string(const))
  end
    
  def option_string(const)
    "<option value='#{const}'> #{const.downcase.capitalize} </option>"
  end
  
end

Shallow Copy using Prototypes Extend

// description of your code here
Shallow copy of an array in Javascript using Prototype's Object.extend !!!

pointz = Object.extend([], points)

Deletion of a marker with a button on the Info Window

// description of your code here
Need to delete a marker with the help of a delelte button in the Info Window.
For some reason applying a listener for the click in the info window didnt work. Dunno why.
Anyways. Right now we are calling a global method directly from the HTML /.. yuck I know. But it works !


// insert code here..

HTML stuff
  <span id='deleteMarker' onclick="delete_marker($('marker').value)">Delete</span>


// here we are first copying over the points to a temp array and then doing the stuff. Else we get a recursive error !!
  redraw_map: function() {
    pointz = Object.extend([], points)
    mapper.clean_map()
    mapper.addPointsToMap(pointz)
  },


//global function
function delete_marker(id) {
  markers = markers.without(markers[id])
  points = points.without(points[id])
  mapper.redraw_map()
}

create_marker function for google Maps

// description of your code here
create_marker function.

was a pain in the ass(info window was alwasy opening on the latest marker). Till i realized that the variable 'marker' was the same in the global scope. so just putting a 'var' before the marker in the fucntion finally fixed this issue !!!
whew \


  create_marker: function(point) {
    var marker = new GMarker(point)
    GEvent.addListener(marker, 'click', function() {
      html = '<div style="white-space:nowrap; width: 270px;">' + $('markerHTML').innerHTML + '</div>'
      marker.openInfoWindowHtml(html)
    })
    return marker
  },

Yellowing Input Box technique

// how to make input fields a pleasing yellow when the focus is in them and revert them when the focus is not !


// the Javascript 

    '.yellowing' : function(e) {
      e.onfocus = function() {
        e.style.backgroundColor = '#FFFFCC'
      },
      e.onblur = function() {
        e.style.backgroundColor = '#FFFFFF'
      }
    } 

// the CSS

.yellow {
  background-color: '#FFFFCC'
}


// the HTML

	<div class='routeHeading'> Route Information </div>
	<div> Description <input type='text' class='yellowing' id='routeDesc' name='routeDesc'/></div>
	<div> Tags <input type='text' class='yellowing' id='routeTags' name='routeTags'/></div>
	
	<div class='SubmitterHeading'> Submitter Information </div>
	<div> Name <input type='text' class='yellowing' id='submitterName' name='submitterName'/></div>
	<div> e-mail <input type='text' class='yellowing' id='submitterEMail' name='submitterEMail'/></div>

How to reset the map with the new bounds passed in !!

// description of your code here
when we load a new map, we need to reset the zoom of the map if the markers are outside the view port that we currently have. So this code takes care of that


    bounds = new GLatLngBounds
    points.each(function(point){
      bounds.extend(point)
    })
    map.setZoom(map.getBoundsZoomLevel(bounds))

First stable release of BikeToWork - mapper.js

// first stable release of Biketoworks mapper.js
var map
var points = $A()
var polyline = null

var mapper = {
  load: function() {
	  map = new GMap($('map'))
    mapper.initializeMap()		
    mapper.registerBehaviours()		
  },
  
  initializeMap: function(){
    map.setMapType(G_SATELLITE_MAP)
	
	  map.addControl(new GLargeMapControl())
    map.addControl(new GOverviewMapControl(new GSize(200,200)))
    
    var bangalore = new GLatLng(parseFloat(12.921458133100641), parseFloat(77.58471965789795));
		map.centerAndZoom(bangalore, -1)
  },
  
  registerBehaviours: function() {
	  mapper.addZoomLimiter()
	  mapper.addClickListeners()
  },

  addClickListeners: function(){
    GEvent.addListener(map, 'click', function(overlay, point) {
      if(overlay != null) return
      mapper.addPointsToMap($A([new GLatLng(point.y, point.x)]))
    })
  },
  
  load_route : function(request) {
    geopoints = $A(JSON.parse(request.responseText))
    pointz = []
    map.removeOverlay(polyline)
    
    pointz = geopoints.collect(function(geopoint) {
      return new GLatLng(geopoint['longitude'], geopoint['latitude'])
    })
    
    mapper.addPointsToMap(pointz)
  },

  addPointsToMap: function(pointz) {
    pointz.each(function(point){
      map.addOverlay(new GMarker(point))
      points.push(point)
    })
    
    $('distance').innerHTML = mapper.distance(pointz)
    polyline = new GPolyline(points)
    map.addOverlay(polyline)
  },
  
  distance: function(pointz) {
    dist = 0
    for(i = 1; i < pointz.lengh; i++) {
      dist = dist + pointz[i].distanceFrom(pointz[i-1])
    }
    return (dist.toFixed(5))/1000
  },
  
  addZoomLimiter: function() {
    GEvent.addListener(map, 'zoom', function() {
      if(map.getZoomLevel() < -1) { map.zoomTo(-1);}
    });
  },
  
  behaviours : {
    '#submit' : function(e) {
      e.onclick = function() {
        json_points = JSON.stringify(points)
        new Ajax.Request('/map/save_route', { onSuccess : alert("Route saved"), parameters: 'markers=' + json_points })
      }
    },

    '#load' : function(e) {
      e.onclick = function() {
        new Ajax.Request('/map/load_route', { onSuccess: mapper.load_route })
      }
    }
  }
}

Behaviour.addLoadEvent(mapper.load);
Behaviour.register(mapper.behaviours)
« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS