View
1.557
Download
2
Category
Preview:
Citation preview
AT&T, AT&T logo and all AT&T related marks are trademarks of AT&T Intellectual Property and/or AT&T affiliated companies.
Q: How can I enjoy
programming?
http://www.flickr.com/photos/recompile_net/3733132232/
A: Use Vim!
http://www.flickr.com/photos/recompile_net/3732334373/
思考
Thread.new do ビール.飲む()
endThread.new do 宿題.する()
end(Thread.list -[Thread.main]).each { |x| x.join }
class Foo def initialize @greeting = 'world' end
def encode_with(coder) coder['hello'] = @greeting end
def init_with(coder) @greeting = coder['hello'] endend
class Foo def initialize @greeting = 'world' end
def encode_with(coder) coder['hello'] = @greeting end
def init_with(coder) @greeting = coder['hello'] endend
Independentの初期化
class XMLDumper < Psych::Handler def self.dump(object) dumper = new viz = Psych::Visitors::YAMLTree.new({}, dumper) viz << object dumper.doc.to_xml end
attr_reader :doc
def initialize @doc = Nokogiri::XML::Document.new @doc.root = @doc.create_element 'root' @tags = [] @stack = [@doc.root] end
def start_mapping(anchor, tag, implicit, style) tag = @doc.create_element('table') @stack.last << tag @stack << tag end
def end_mapping @stack.pop end
def scalar(value, anchor, tag, *args) @stack.last << @doc.create_element('tr').tap do |tag| tag << @doc.create_element('td', value) end endend
class HTMLDumper < XMLDumper def initialize @doc = Nokogiri::HTML::Document.new @doc.root = @doc.create_element('html') @doc.root << @doc.create_element('body') @tags = [] @stack = [@doc.root.children.first] endend
YAML, JSON, XML と HTML
Psych.dump Foo.newPsych.to_json Foo.newXMLDumper.dump Foo.newHTMLDumper.dump Foo.new
module Marshalable module ClassMethods def _load data x = allocate x.init_with Marshal.load data x end end
def self.included klass klass.extend ClassMethods end
def _dump o coder = {} encode_with coder Marshal.dump coder endend
class Foo; include Marshalable; end
YAML, JSON, XML, HTML と Marshal
Psych.dump Foo.newPsych.to_json Foo.newXMLDumper.dump Foo.newHTMLDumper.dump Foo.newMarshal.dump Foo.new
クエリの作成
connection.execute('CREATE TABLE foo(id INTEGER)')
connection.execute('INSERT INTO foo (id) VALUES (?)', [10])
ステートメントの用意
stmt = connection.prepare('SELECT * FROM foo WHERE id = ?')
stmt.bind_param(1, 10)
stmt.each do |row| p rowend
struct sqlite3_vfs { int iVersion; /* Structure version number */ int szOsFile; /* Size of subclassed sqlite3_file */ int mxPathname; /* Maximum file pathname length */ sqlite3_vfs *pNext; /* Next registered VFS */ const char *zName; /* Name of this virtual file system */ void *pAppData; /* Pointer to application-specific data */ int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*, int flags, int *pOutFlags); int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut); int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void); void (*xDlClose)(sqlite3_vfs*, void*); int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); int (*xSleep)(sqlite3_vfs*, int microseconds); int (*xCurrentTime)(sqlite3_vfs*, double*); int (*xGetLastError)(sqlite3_vfs*, int, char *); /* New fields may be appended in figure versions. The iVersion ** value will increment whenever this happens. */};
その1: APIを読もう
static int rbFile_close(sqlite3_file * ctx){ rubyFilePtr rfile = (rubyFilePtr)ctx; VALUE file = rfile->file; rb_funcall(file, rb_intern("close"), 0); return SQLITE_OK;}
class VFS < SQLite3::VFS def open(name, flags) OurFile.new(name, flags) endend
class OurFile def read(...); ... end def write(...); ... endend
class EvilVFS < SQLite3::VFS def open name, flags DATABase.new name, flags endend
class DATABase < SQLite3::VFS::File def initialize name, flags super @store = File.open(name, File::RDWR | File::CREAT) @offset = 0
if File.expand_path(__FILE__) == name @store.seek DATA.pos @offset = DATA.pos end end
def close @store.close end
def read amt, offset @store.seek(offset + @offset) @store.read amt end
def write data, offset @store.seek(offset + @offset) @store.write data end
def sync opts @store.fsync end
def file_size File.size(@store.path) - @offset endend
SQLite3.vfs_register(EvilVFS.new)db = SQLite3::Database.new(__FILE__, nil, 'EvilVFS')
db.execute(<<-eosql) create table if not exists users(id integer primary key, name string)eosql
100.times { db.execute(<<-eosql, 'tenderlove') insert into users(name) values (?) eosql}
p db.execute('select count(*) from users')
__END__
ソースコードはここhttp://gist.github.com/319224/
エンコーディングrequire 'sqlite3'
db = SQLite3::Database.new(':memory:')
db.execute('CREATE TABLE foo(id INTEGER, name VARCHAR)')db.execute('INSERT INTO foo (id, name) VALUES (?,?)',[10,'hello world'])
rows = db.execute('SELECT name FROM foo')p rows.first.first.encoding # => #<Encoding:UTF-8>
Encoding.default_internal = 'EUC-JP'
rows = db.execute('SELECT name FROM foo')p rows.first.first.encoding # => #<Encoding:EUC-JP>
エンコーディングrequire 'sqlite3'
db = SQLite3::Database.new(':memory:')
db.execute('CREATE TABLE foo(id INTEGER, name VARCHAR)')db.execute('INSERT INTO foo (id, name) VALUES (?,?)',[10,'hello world'])
rows = db.execute('SELECT name FROM foo')p rows.first.first.encoding # => #<Encoding:UTF-8>
Encoding.default_internal = 'EUC-JP'
rows = db.execute('SELECT name FROM foo')p rows.first.first.encoding # => #<Encoding:EUC-JP>
エンコーディングrequire 'sqlite3'
db = SQLite3::Database.new(':memory:')
db.execute('CREATE TABLE foo(id INTEGER, name VARCHAR)')db.execute('INSERT INTO foo (id, name) VALUES (?,?)',[10,'hello world'])
rows = db.execute('SELECT name FROM foo')p rows.first.first.encoding # => #<Encoding:UTF-8>
Encoding.default_internal = 'EUC-JP'
rows = db.execute('SELECT name FROM foo')p rows.first.first.encoding # => #<Encoding:EUC-JP>
Ruby.PHP()
Phuby::Runtime.php do |rt| rt.eval('$v = strlen("PHP IS AWESOME");') puts rt['v'] # => 14end
Ruby.PHP()
Phuby::Runtime.php do |rt| rt.eval('$foo = array();') rt.eval('$foo["hello"] = "world";')
foo = rt['foo'] # => #<Phuby::Array:0x101f8f848> p foo['hello'] # => ‘world’end
$PHP->Ruby();
class FUN def times puts "hello" endend
Phuby::Runtime.php do |rt| rt['fun'] = FUN.new rt.eval('$fun->times();') # => helloend
#!/usr/bin/env ruby
require 'rubygems'require 'phuby'require 'rack'
### Rack::Phrack is a Rack handler that will evaulate and serve PHP files.
class Rack::Phrack < Rack::File class Events < Struct.new(:code, :headers, :body) def write string; body << string; end def send_headers response_code; end
def header value, op k, v = value.split(': ', 2) self.code = 302 if k == 'Location' headers[k] = [headers[k], Rack::Utils.unescape(v)].compact.join "\n" end end
def call env events = Events.new 200, {}, '' file = File.join @root, env['PATH_INFO'] file = File.join file, "index.php" if File.directory?(file)
return super unless file =~ /php$/
Dir.chdir(File.dirname(file)) do Phuby::Runtime.php do |rt| rt.eval "date_default_timezone_set('America/Los_Angeles');" # *shrug*
{ Rack::Utils.parse_query(env['QUERY_STRING']) => "_GET", Rack::Utils.parse_query(env['rack.input'].read) => "_POST", Rack::Utils.parse_query(env['HTTP_COOKIE'], ';') => "_COOKIE", }.each do |from, to| from.each { |k,v| rt[to][k] = v } end
env.each { |k,v| rt['_SERVER'][k] = v || '' unless k =~ /^rack/ } rt["_SERVER"]['REQUEST_URI'] = env['PATH_INFO']
rt.with_events(events) { open(file) { |f| rt.eval f } } # RUN! end end events.to_a endend
Rack::Handler::WEBrick.run(Rack::Phrack.new(ARGV[0] || Dir.pwd), :Port => 10101)
Recommended