Monday, 30 June 2014

found it #retro

#50s #60s #listen #retro http://www.ultraswank.net/compilation/space-age-lounge-volume-3-love-at-first-flight/

Thursday, 26 June 2014

Neil's Idea

class X
attr_accessor :foo
def [](key)
__send__ key.to_sym if [:foo].include? key.to_sym
end
def []=(key, value)
__send__ :"#{key}=", value if [:foo].include? key.to_sym
end
end
x = X.new
x[:foo] = 123
puts x[:foo]
x.foo = "works"
p x.foo
view raw gistfile1.rb hosted with ❤ by GitHub

Sunday, 22 June 2014

Hash to_snake_keys

class Hash
# Recursively converts CamelCase and camelBack JSON-style hash keys to
# Rubyish snake_case, suitable for use during instantiation of Ruby
# model attributes.
#
def to_snake_keys(value = self)
case value
when Array
value.map { |v| to_snake_keys(v) }
when Hash
Hash[value.map { |k, v| [underscore_key(k), to_snake_keys(v)] }]
else
value
end
end
private
def underscore_key(k)
if k.is_a? Symbol
underscore(k.to_s).to_sym
elsif k.is_a? String
underscore(k)
else
k # Plissken can't snakify anything except strings and symbols
end
end
def underscore(string)
string.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
downcase
end
end
view raw gistfile1.rb hosted with ❤ by GitHub

Thursday, 19 June 2014

Ruby Timeouts

status = Timeout::timeout(5) {
sleep(333)
}
p status
#Timeout::Error: execution expired
view raw Timeouts hosted with ❤ by GitHub

Ruby Pre-defined variables

prev - next - index

Pre-defined variables



$!
The exception information message. raise sets this variable.
$@
The backtrace of the last exception, which is the array of the string that indicates the point where methods invoked from. The elements in the format like:
"filename:line"
or
"filename:line:in `methodname'"
(Mnemonic: where exception occurred at.)
$&
The string matched by the last successful pattern match in this scope, or nil if the last pattern match failed. (Mnemonic: like & in some editors.) This variable is read-only.
$`
The string preceding whatever was matched by the last successful pattern match in the current scope, or nil if the last pattern match failed. (Mnemonic: ` often precedes a quoted string.) This variable is read-only.
$'
The string following whatever was matched by the last successful pattern match in the current scope, or nil if the last pattern match failed. (Mnemonic: ' often follows a quoted string.)
$+
The last bracket matched by the last successful search pattern, or nil if the last pattern match failed. This is useful if you don't know which of a set of alternative patterns matched. (Mnemonic: be positive and forward looking.)
$1, $2...
Contains the subpattern from the corresponding set of parentheses in the last successful pattern matched, not counting patterns matched in nested blocks that have been exited already, or nil if the last pattern match failed. (Mnemonic: like \digit.) These variables are all read-only.
$~
The information about the last match in the current scope. Setting this variables affects the match variables like $&$+$1$2.. etc. The nth subexpression can be retrieved by $~[nth]. (Mnemonic: ~ is for match.) This variable is locally scoped.
$=
The flag for case insensitive, nil by default. (Mnemonic: = is for comparison.)
$/
The input record separator, newline by default. Works like awk's RS variable. If it is set to nil, whole file will be read at once. (Mnemonic: / is used to delimit line boundaries when quoting poetry.)
$\
The output record separator for the print and IO#write. The default is nil. (Mnemonic: It's just like /, but it's what you get "back" from Ruby.)
$,
The output field separator for the print. Also, it is the default separator for Array#join. (Mnemonic: what is printed when there is a , in your print statement.)
$;
The default separator for String#split.
$.
The current input line number of the last file that was read.
$<
The virtual concatenation file of the files given by command line arguments, or stdin (in case no argument file supplied). $<.file returns the current filename. (Mnemonic: $< is a shell input source.)
$>
The default output for printprintf$stdout by default. (Mnemonic: $> is for shell output.)
$_
The last input line of string by gets or readline. It is set to nil if gets/readline meet EOF. This variable is locally scoped. (Mnemonic: partly same as Perl.)
$0
Contains the name of the file containing the Ruby script being executed. On some operating systems assigning to $0 modifies the argument area that the ps(1) program sees. This is more useful as a way of indicating the current program state than it is for hiding the program you're running. (Mnemonic: same as sh and ksh.)
$*
Command line arguments given for the script. The options for Ruby interpreter are already removed. (Mnemonic: same as sh and ksh.)
$$
The process number of the Ruby running this script. (Mnemonic: same as shells.)
$?
The status of the last executed child process.
$:
The array contains the list of places to look for Ruby scripts and binary modules by load or require. It initially consists of the arguments to any -I command line switches, followed by the default Ruby library, probabl "/usr/local/lib/ruby", followed by ".", to represent the current directory. (Mnemonic: colon is the separators for PATH environment variable.)
$"
The array contains the module names loaded by require. Used for prevent require from load modules twice. (Mnemonic: prevent files to be doubly quoted(loaded).)
$DEBUG
The status of the -d switch.
$FILENAME
Same as $<.filename.
$LOAD_PATH
The alias to the $:.
$stdin
The current standard input.
$stdout
The current standard output.
$stderr
The current standard error output.
$VERBOSE
The verbose flag, which is set by the -v switch to the Ruby interpreter.
option variables
The variables which names are in the form of $-?, where ? is the option character, are called option variables and contains the information about interpreter command line options.
$-0
The alias to the $/.
$-a
True if option -a is set. Read-only variable.
$-d
The alias to the $DEBUG.
$-F
The alias to the $;.
$-i
In in-place-edit mode, this variable holds the extention, otherwise nil. Can be assigned to enable (or disable) in-place-edit mode.
$-I
The alias to the $:.
$-l
True if option -lis set. Read-only variable.
$-p
True if option -pis set. Read-only variable.
$-v
The alias to the $VERBOSE.

Pre-defined global constants



TRUE
The typcal true value. All non-false values (everything except nil and false) is true in Ruby.
FALSE
The false itself.
NIL
The nil itself.
STDIN
The standard input. The default value for $stdin.
STDOUT
The standard output. The default value for $stdout.
STDERR
The standard error output. The default value for $stderr.
ENV
The hash-like object contains current environment variables. Setting a value in ENV changes the environment for child processes.
ARGF
The alias to the $<.
ARGV
The alias to the $*.
DATA
The file object of the script, pointing just after the __END__. Not defined unless the script is not read from the file.
VERSION
The Ruby version string.
RUBY_RELEASE_DATE
The relase date string.
RUBY_PLATFORM
The platform identifier.

prev - next - index



http://web.njit.edu/all_topics/Prog_Lang_Docs/html/ruby/variable.html

Wednesday, 11 June 2014

Backbone Rails Blog example

A small example using rails-backbone gem

Example Usage

Created a new rails application called blog.

rails new blog

Edit your Gemfile and add

gem 'rails-backbone'

Install the gem and generate scaffolding.

bundle install
rails g backbone:install
rails g scaffold Post title:string content:string
rake db:migrate
rails g backbone:scaffold Post title:string content:string

You now have installed the backbone-rails gem, setup a default directory structure for your frontend backbone code. Then you generated the usual rails server side crud scaffolding and finally generated backbone.js code to provide a simple single page crud app. You have one last step:

Edit your posts index view app/views/posts/index.html.erb with the following contents:

<div id="posts"></div>

<script type="text/javascript">
  $(function() {
    // Blog is the app name
    window.router = new Blog.Routers.PostsRouter({posts: <%= @posts.to_json.html_safe -%>});
    Backbone.history.start();
  });
</script>

If you prefer haml, this is equivalent to inserting the following code into app/views/posts/index.html.haml:

#posts

:javascript
  $(function() {
    // Blog is the app name
    window.router = new Blog.Routers.PostsRouter({posts: #{@posts.to_json.html_safe}});
    Backbone.history.start();
  });

Now start your server rails s and browse to localhost:3000/posts You should now have a fully functioning single page crud app for Post models.

####With Rails 4:#### If you are using the default Rails 4 scaffold generators, you will need to adjust the default JSON show view (IE, 'show.json') to render the 'id' attribute.

default rails generated show.json.jbuilder

json.extract! @post, :title, :content, :created_at, :updated_at

Change it to add id attribute as well

json.extract! @post, :id, :title, :content, :created_at, :updated_at

Without adjusting the JSON show view, you will be redirected to a "undefined" url after creating an object.

https://github.com/msroot/rails-backbone-example/

view raw gistfile1.md hosted with ❤ by GitHub

Ruby on Rails API Search

Install the plugin

hit rd and space




 https://chrome.google.com/webstore/detail/ruby-on-rails-api-search/nbhhppofdccphcpbilanmljnlkmbgike?hl=en

Thursday, 5 June 2014

webcam-photos-with-ruby

# require 'av_capture'
#
# # Create a recording session
# session = AVCapture::Session.new
#
# # Find the first video capable device
# dev = AVCapture.devices.find(&:video?)
#
# # Output the camera's name
# $stderr.puts dev.name
#
# # Connect the camera to the recording session
# session.run_with(dev) do |connection|
#
# # Capture an image and write it to $stdout
# $stdout.write connection.capture
# end
# require 'av_capture'
# require 'io/console'
#
# session = AVCapture::Session.new
# dev = AVCapture.devices.find(&:video?)
#
# session.run_with(dev) do |connection|
# loop do
# case $stdin.getch
# when 'q' then break # quit when you hit 'q'
# else
# IO.popen("open -g -f -a /Applications/Preview.app", 'w') do |f|
# f.write connection.capture
# end
# end
# end
# end
# Server code
# Here is our server code:
require 'av_capture'
require 'drb'
class PhotoServer
attr_reader :photo_request, :photo_response
def initialize
@photo_request = Queue.new
@photo_response = Queue.new
@mutex = Mutex.new
end
def take_photo
@mutex.synchronize do
photo_request << "x"
photo_response.pop
end
end
end
server = PhotoServer.new
Thread.new do
session = AVCapture::Session.new
dev = AVCapture.devices.find(&:video?)
session.run_with(dev) do |connection|
while server.photo_request.pop
server.photo_response.push connection.capture
end
end
end
URI = "druby://localhost:8787"
DRb.start_service URI, server
DRb.thread.join
# Client Code
# ------------------------------------------------
require 'drb'
SERVER_URI = "druby://localhost:8787"
photoserver = DRbObject.new_with_uri SERVER_URI
print photoserver.take_photo
# ------------------------------
# Running the code
# In one terminal, run the server code like this:
#
# $ ruby server.rb
# Then in another terminal, run the client code like this:
# $ ruby client.rb | open -f -a /Applications/Preview.app
# You should have a photo show up in Preview.app. You can kill the server program by doing Ctrl-C.
http://tenderlovemaking.com/2014/03/26/webcam-photos-with-ruby.html
view raw gistfile1.rb hosted with ❤ by GitHub