Wednesday, 31 July 2013

ruby_metaprogramming

# class.instance_methods(false)
class Rubyist
# the code in the following method definition is executed later,
# when you eventually call the method
def what_does_he_do
@person = 'A Rubyist'
'Ruby programming'
end
end
an_object = Rubyist.new
puts an_object.class # => Rubyist
puts an_object.class.instance_methods(false) # => what_does_he_do
an_object.what_does_he_do
puts an_object.instance_variables # => @person
#respond_to
obj = Object.new
if obj.respond_to?(:program)
obj.program
else
puts "Sorry, the object doesn't understand the 'program' message."
end
#send
class Rubyist
def welcome(*args)
"Welcome " + args.join(' ')
end
end
obj = Rubyist.new
puts(obj.send(:welcome, "famous", "Rubyists")) # => Welcome famous Rubyists
#:method_missing
class Rubyist
def method_missing(m, *args, &block)
str = "Called #{m} with #{args.inspect}"
if block_given?
puts str + " and also a block: #{block}"
else
puts str
end
end
end
# => Called anything with []
Rubyist.new.anything
# => Called anything with [3, 4] and also a block: #<Proc:0xa63878@tmp.rb:12>
Rubyist.new.anything(3, 4) { something }
#http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_2.html

ECMAScript 5: Tamper proofing objects

var o = {
foo: "bar"
};
// adding a new property normally:
o.hey = "guys";
// preventing further extensions:
Object.preventExtensions(o);
// silent error, or TypeError under strict mode:
o.anotherProp = "This will fail!";
// existing properties can still be changed:
o.hey = "gals";
var o = {
foo: "bar"
};
// adding a new property normally:
o.hey = "guys";
// deleting a property normally:
delete o.hey;
// sealing the object:
Object.seal(o);
// silent failure, or TypeError under strict mode:
o.anotherProp = "This will fail!";
// existing properties can still be changed if they were writable:
o.foo = "baz";
// silent failure, or TypeError under strict mode:
delete o.foo;
//We can do everything Object.seal does, but also protect data properties
//from being overwritten by using the Object.freeze method.
var o = {
foo: "bar"
};
// adding a new property normally:
o.hey = "guys";
// deleting a property normally:
delete o.hey;
// sealing the object:
Object.freeze(o);
// silent failures, or TypeErrors under strict mode:
o.anotherProp = "This will fail!";
o.foo = "baz";
delete o.foo;
var o = { foo: "bar" };
Object.preventExtensions(o);
Object.defineProperty(o, "foo", {
writable: false,
configurable: false
});
// Object.isFrozen(o) === true
//http://www.jimmycuadra.com/posts/ecmascript-5-tamper-proofing-objects
view raw gistfile1.js hosted with ❤ by GitHub

instance_values

:instance_variables
class Gift
def initialize
@name = "book"
@price = 15.95
end
end
gift = Gift.new
hash = {}
gift.instance_variables.each {|var| hash[var.to_s.delete("@")] = gift.instance_variable_get(var) }
p hash # => {"name"=>"book", "price"=>15.95}
:attributes.to_options
App.first.attributes.to_options
:instance_variable_get
class Fred
def initialize(p1, p2)
@a, @b = p1, p2
end
end
fred = Fred.new('cat', 99)
fred.instance_variable_get(:@a) #=> "cat"
fred.instance_variable_get("@b") #=> 99
:instance_values
Gift.new.instance_values # => {"name"=>"book", "price"=>15.95}
:attributes
App.first.attributes
view raw instance_values hosted with ❤ by GitHub

Active Record loves blocks

#http://blog.plataformatec.com.br/page/3/
#Active Record associations also love blocks
#We talked about using blocks when building an Active Record object using new or create, but associations like belongs_to or #has_many also work with that, when calling build or create on them:
class User < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :user
end
# has_many
user = User.first
user.posts.build do |post|
post.title = "Active Record <3 Blocks"
post.body = "I can give tap a break! <3 <3 <3"
end
# belongs_to
post = Post.first
post.build_user do |user|
user.name = "John Doe <3 blocks"
user.username = "john.doe"
user.password = "john123"
end

instance_eval && class_eval

class Person
end
Person.class_eval do
def say
"malakias"
end
end
me = Person.new
me.say
class Person
end
Person.instance_eval do
def go_for_cofe?
true
end
end
Person.go_for_cofe?

Keyboard Shortcuts for Bash


Ctrl + AGo to the beginning of the line you are currently typing on
Ctrl + EGo to the end of the line you are currently typing on
Ctrl + L              Clears the Screen, similar to the clear command
Ctrl + UClears the line before the cursor position. If you are at the end of the line, clears the entire line.
Ctrl + HSame as backspace
Ctrl + RLet’s you search through previously used commands
Ctrl + CKill whatever you are running
Ctrl + DExit the current shell
Ctrl + ZPuts whatever you are running into a suspended background process. fg restores it.
Ctrl + WDelete the word before the cursor
Ctrl + KClear the line after the cursor
Ctrl + TSwap the last two characters before the cursor
Esc + TSwap the last two words before the cursor
Alt + FMove cursor forward one word on the current line
Alt + BMove cursor backward one word on the current line
TabAuto-complete files and folder names
http://www.howtogeek.com/howto/ubuntu/keyboard-shortcuts-for-bash-command-shell-for-ubuntu-debian-suse-redhat-linux-etc/

wget links

array=(
"http://something.come/videos/somevideo.mp4"
"http://something.come/videos/somevideo.mp4"
"http://something.come/videos/somevideo.mp4"
"http://something.come/videos/somevideo.mp4"
"http://something.come/videos/somevideo.mp4"
"http://something.come/videos/somevideo.mp4"
"http://something.come/videos/somevideo.mp4"
)
for i in "${array[@]}"
do
wget $i
done
view raw gistfile1.txt hosted with ❤ by GitHub

seed

sed 's/FindThisWord/ReplaceWithThisWord/g' file.txt
sed 's/Apple/MacLife/g' sample.txt
#http://www.maclife.com/article/columns/terminal_101_find_and_replace_using_sed
sed -n 's/Apple/MacLife/gpw output.txt' sample.txt
view raw gistfile1.txt hosted with ❤ by GitHub


via Instagram http://instagram.com/p/ca9hzKr5da/

Monday, 29 July 2013

jQuery clone one element

<div id="contition_container">
<div class="contition-group contition-group-style form-group">
<select class="keys form-control" style="width: 30%; margin-right: 10px; float:left">
<option value="">Keys</option>
<% @category.app.data_to_json.map { |o| o.keys}.flatten.uniq.each do |k|%>
<option value="<%= k %>"><%= k %></option>
<% end %>
</select>
<select class="operators form-control" style="width: 10%; margin-right: 10px; float:left">
<option value=">">Operators</option>
<option value=">">></option>
<option value=">">=></option>
<option value=">"><</option>
<option value=">"><=</option>
<option value=">">==</option>
<option value=">">!=</option>
</select>
<input type="text" class="form-control contitions" placeholder="value" style="float:left">
<select class="logical form-control" style="width: 10%; margin-right: 10px; float:left">
<option value=">">Logical</option>
<option value=">">and</option>
<option value=">">not</option>
</select>
<a class="clone btn btn-primary" style="float:left">more</a>
</div> </div>
<script type="text/javascript" charset="utf-8">
$(".clone").click(function(){
$(".contition-group").clone().prependTo("#contition_container")
$(".contition-group").last().removeClass("contition-group")
$(".clone").first().fadeOut("slow")
});
</script>

Pry within rails4 console

#config/application.rb
module YourApp
class Application < Rails::Application
console do
require "pry"
config.console = Pry
end
end
end
#add to the gemfile
group :development, :test do
gem 'pry'
end
#rails console
rails c
cd YourModel
#read more
#https://github.com/pry/pry
view raw gistfile1.rb hosted with ❤ by GitHub

Saturday, 27 July 2013

Upgrading to Bootstrap 3 RC1 with Rails 4.0.0.rc1

#Add in application helper for bootstrap_flash
module ApplicationHelper
ALERT_TYPES = [:error, :info, :success, :warning]
def bootstrap_flash
flash_messages = []
flash.each do |type, message|
next if message.blank?
type = :success if type == :notice
type = :error if type == :alert
next unless ALERT_TYPES.include?(type)
Array(message).each do |msg|
text = content_tag(:div,
content_tag(:button, raw("&times;"), :class => "close", "data-dismiss" => "alert") +
msg.html_safe, :class => "alert fade in alert-#{type}")
flash_messages << text if msg
end
end
flash_messages.join("\n").html_safe
end
end
#Add to Gem file
gem "sass-rails", "~> 4.0.0"
gem 'anjlab-bootstrap-rails', :require => 'bootstrap-rails',
:github => 'anjlab/bootstrap-rails',
:branch => '3.0.0'
rake assets:precompile

javascript Module Pattern example

http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html
var MODULE = (function (my) {
my.myMethod = function () {
console.log("myMethod");
};
return my;
}(MODULE || {}));

Overwrite models attributes at Serializer with rails 4

class AppSerializer < ActiveModel::Serializer
attributes :hashid, :updated_at
def updated_at
object.updated_at.to_time.to_i
end
def attributes
data = super
data[:attribute] = edit_app_url(object)
data
end
end
view raw gistfile1.rb hosted with ❤ by GitHub

Friday, 26 July 2013

rails generate uniqie hash

class App < ActiveRecord::Base
before_create :generate_hash_id
private
def generate_hash_id
begin
self.hash_id = SecureRandom.hex(30)
end while self.class.exists?(hash_id: hash_id)
end
end

Sunday, 21 July 2013

Greeks.in the app that locates Greeks near you!






rails annotate gem

#use annotate gem to annotate your models
#add gem 'annotate' and annotate from app dir it will generate this in all models
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# uid :text
# name :string(255)
# link :string(255)
# username :string(255)
# hometown :string(255)
# location :string(255)
# quotes :text
# gender :string(255)
# created_at :datetime
# updated_at :datetime
# email :string(255) default(""), not null
# encrypted_password :string(128) default(""), not null
# reset_password_token :string(255)
# reset_password_sent_at :datetime
# remember_created_at :datetime
# sign_in_count :integer default(0)
# current_sign_in_at :datetime
# last_sign_in_at :datetime
# current_sign_in_ip :string(255)
# last_sign_in_ip :string(255)
# token :text
# provider :string(255)
# image :string(255)
# latitude :float
# longitude :float
# token_local :text
#

Tuesday, 16 July 2013

newrelic_rpm with Rails 4 on heroku

There is a bug in newrelics config file

The solution:



1. in config/newrelic.yml

line 46  replace

app_name: <%= ENV["NEW_RELIC_APP_NAME"] %>

view is var in defined in heroku

blah:(master) ✗ heroku config
DATABASE_URL                 =>
HEROKU_POSTGRESQL_COBALT_URL =>
NEW_RELIC_LICENSE_KEY        =>
NEW_RELIC_LOG                =>
PAPERTRAIL_API_TOKEN         =>

set the var

heroku config:set NEW_RELIC_APP_NAME=new_app

also in ~/.profile

export NEW_RELIC_APP_NAME=my_app

Sunday, 14 July 2013

Ιθάκη

Σα βγεις στον πηγαιμό για την Ιθάκη,
να εύχεσαι να’ναι μακρύς ο δρόμος,
γεμάτος περιπέτειες, γεμάτος γνώσεις.
Τους Λαιστρυγόνας και τους Κύκλωπας,
τον θυμωμένο Ποσειδώνα μη φοβάσαι,
τέτοια στον δρόμο σου ποτέ σου δεν θα βρεις,
αν μέν' η σκέψις σου υψηλή, αν εκλεκτή
συγκίνησις το πνεύμα και το σώμα σου αγγίζει.
Τους Λαιστρυγόνας και τους Κύκλωπας,
τον άγριο Ποσειδώνα δεν θα συναντήσεις,
αν δεν τους κουβανείς μες στην ψυχή σου,
αν η ψυχή σου δεν τους στήνει εμπρός σου.
Να εύχεσαι να’ναι μακρύς ο δρόμος.
Πολλά τα καλοκαιρινά πρωιά να είναι
που με τι ευχαρίστηση, με τι χαρά
θα μπαίνεις σε λιμένας πρωτοειδωμένους·
να σταματήσεις σ' εμπορεία Φοινικικά,
και τες καλές πραγμάτειες ν' αποκτήσεις,
σεντέφια και κοράλλια, κεχριμπάρια κ' έβενους,
και ηδονικά μυρωδικά κάθε λογής,
όσο μπορείς πιο άφθονα ηδονικά μυρωδικά·
σε πόλεις Aιγυπτιακές πολλές να πας,
να μάθεις και να μάθεις απ' τους σπουδασμένους.
Πάντα στον νου σου να’χεις την Ιθάκη.
Το φθάσιμον εκεί είν ο προορισμός σου.
Aλλά μη βιάζεις το ταξίδι διόλου.
Καλλίτερα χρόνια πολλά να διαρκέσει·
και γέρος πια ν' αράξεις στο νησί,
πλούσιος με όσα κέρδισες στον δρόμο,
μη προσδοκώντας πλούτη να σε δώσει η Ιθάκη.
Η Ιθάκη σ' έδωσε τ' ωραίο ταξίδι.
Χωρίς αυτήν δεν θα βγαινες στον δρόμο.
Άλλα δεν έχει να σε δώσει πια.
Κι αν πτωχική την βρεις, η Ιθάκη δεν σε γέλασε.
Έτσι σοφός που έγινες, με τόση πείρα,
ήδη θα το κατάλαβες η Ιθάκες τι σημαίνουν.
view raw gistfile1.txt hosted with ❤ by GitHub

Δεν το γράφουν τα λεξικά, αλλά μου το είπαν ψιθυριστά οι σειρήνες της ζωής

ΥΓ. Δεν το γράφουν τα λεξικά, αλλά μου το είπαν ψιθυριστά οι σειρήνες της ζωής,
η λέξη Κρίση σημαίνει επίσης, ευκαιρία για νέες ευκαιρίες και απελευθέρωση δημιουργικότητας.
ΥΓ. Και ποτέ δεν ξεχνώ: …Πάντα στο νου σου νάχεις την Ιθάκη…Το φθάσιμον εκεί είναι ο
προορισμός σου…Aλλά μη βιάζεις το ταξίδι διόλου…
http://www.godimitris.gr/index.php?mact=News,cntnt01,detail,0&cntnt01articleid=1909&cntnt01origid=15&cntnt01lang=el_GR&cntnt01returnid=72&hl=greek
view raw gistfile1.txt hosted with ❤ by GitHub

Friday, 12 July 2013

jquery's mouse over rotate

.cross-browser .feature-box-image{
background: url('i/feature-sprites.png') -278px 0px no-repeat;
-webkit-transition: all 0.4s;
transition: all 0.4s;
position: relative;
z-index: 10;
}
.cross-browser .feature-box-image:hover {
-webkit-transition: all 0.7s linear;
-webkit-transform: rotate(6.28rad);
transition: all 0.7s;
transform: rotate(6.28rad);
}

Tuesday, 2 July 2013

Adapt.js responsive without bootstrap

What is this?


 Adapt.js is a lightweight (848 bytes minified) JavaScript file that determines which CSS file to load before the browser renders a page. If the browser tilts or resizes, Adapt.js simply checks its width, and serves only the CSS that is needed, when it is needed.



 http://adapt.960.gs/


// Edit to suit your needs.
var ADAPT_CONFIG = {
  // Where is your CSS?
  path: 'assets/css/',

  // false = Only run once, when page first loads.
  // true = Change on window resize and page tilt.
  dynamic: true,

  // Optional callback... myCallback(i, width)
  callback: myCallback,

  // First range entry is the minimum.
  // Last range entry is the maximum.
  // Separate ranges by "to" keyword.
  range: [
    '0px    to 760px  = mobile.css',
    '760px  to 980px  = 720.css',
    '980px  to 1280px = 960.css',
    '1280px to 1600px = 1200.css',
    '1600px to 1920px = 1560.css',
    '1940px to 2540px = 1920.css',
    '2540px           = 2520.css'
  ]
};