repo
string | commit
string | message
string | diff
string |
---|---|---|---|
simonwhitaker/goo-website
|
5709d9ddb08271162e5c354654e748e256494025
|
Changing blog design to black background
|
diff --git a/artwork/open-quote.opacity b/artwork/open-quote.opacity
new file mode 100644
index 0000000..5c60091
Binary files /dev/null and b/artwork/open-quote.opacity differ
diff --git a/src/content/blog/0002-subversion-rev.md b/src/content/blog/0002-subversion-rev.md
index c3e6cd9..220d7a0 100644
--- a/src/content/blog/0002-subversion-rev.md
+++ b/src/content/blog/0002-subversion-rev.md
@@ -1,30 +1,46 @@
---
kind: article
created_at: 2010-08-03
title: Append Subversion revision to an iPhone appâs bundle version at build time
---
Here's a dirty hack to append the current Subversion revision to the version number of an iPhone app
automatically at build time. If your Info.plist specifies the version as 1.0 and your local Subversion
repository is at revision 36, the version number in your compiled app will be 1.0.36.
To use:
1. In Xcode control-click your target and choose Add > New Build Phase > New Run Script Build Phase
2. Leave shell set to /bin/sh. Copy the code below (or grab from [gist](http://gist.github.com/506429)) and paste it into the Script panel
3. Close the dialog
4. Drag the new build phase action so that it appears first in the list of build actions
5. Build your app
-<script src="http://gist.github.com/506429.js?file=gistfile1.sh"></script>
+Here's the code:
+
+ # Get location of unparsed Info.plist
+ GS_INFO_PLIST_INPUT=$(basename "$INFOPLIST_FILE" .plist)
+
+ # Get location of parsed Info.plist
+ GS_INFO_PLIST_PATH="$BUILT_PRODUCTS_DIR/$FULL_PRODUCT_NAME/Info"
+
+ # Get version number from unparsed Info.plist
+ GS_VERSION=$(defaults read "$PROJECT_DIR/$GS_INFO_PLIST_INPUT" CFBundleVersion)
+
+ # Append local SVN revision number
+ export GS_NEW_VERSION=$GS_VERSION.$(svnversion)
+ echo Version is $GS_NEW_VERSION
+
+ # Write new version number to parsed Info.plist
+ defaults write "$GS_INFO_PLIST_PATH" CFBundleVersion $GS_NEW_VERSION
This is a bit of a dirty one, but it works for me. If you have suggested improvements I'm all ears so please
leave a comment.
For more on the output of svnversion, run:
$ svnversion --help
diff --git a/src/content/blog/0003-spot-the-bug.md b/src/content/blog/0003-spot-the-bug.md
index 30d8ac2..87140a9 100644
--- a/src/content/blog/0003-spot-the-bug.md
+++ b/src/content/blog/0003-spot-the-bug.md
@@ -1,9 +1,15 @@
---
kind: article
created_at: 2010-08-24
title: Spot the bug
---
This code is supposed to show an instructions view when you rotate from landscape to portrait, but sometimes it doesn't quite perform as expected. Can you see why?
-<script src="http://gist.github.com/546623.js?file=gistfile1.m"></script>
\ No newline at end of file
+ - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
+ {
+ if (UIInterfaceOrientationIsLandscape(fromInterfaceOrientation)) {
+ // Fade in instructions
+ [self setInstructionsOpacity:1.0 overTime:0.5];
+ }
+ }
\ No newline at end of file
diff --git a/src/content/blog/0005-nanoc.md b/src/content/blog/0005-nanoc.md
index b5d4b2d..950be05 100644
--- a/src/content/blog/0005-nanoc.md
+++ b/src/content/blog/0005-nanoc.md
@@ -1,74 +1,127 @@
---
title: Site construction and blogging with nanoc
kind: article
created_at: 2010-10-20
---
Since its inception, the Goo Software website has been written as static HTML and the
blog's been running on a Wordpress installation. It's worked fine but I've never been
happy with the setup. On the blog side, Wordpress is OK but heavyweight for our modest
needs, and on the main site maintaining everything as static HTML is a pain. Even with
only a few pages there's a load of boilerplate code that needs to be kept in sync
across pages, and on the front page there's a load of duplicate code around the
portfolio.
I'd toyed with the idea of using [Django][django] to run the site, which would allow me
to use Django's templates system to share boilerplate code across pages, and Django's
ORM to model stuff like apps for the portfolio, but that's getting seriously heavyweight
for a site that seldom changes. I needed something in between static and Django. And then
I found [nanoc][nanoc].
## What is nanoc?
nanoc is "a Ruby site compiler that generates static HTML". In essence, you provide content
as *layouts* (templates) and *items* (pages), and nanoc uses those building blocks to
generate your site. The back end strikes just the right balance between flexibility and
simplicity, and it's nicely extensible so you're only a few lines of Ruby away from any
missing functionality that you can't do without.
## Basic workflow
Using nanoc is really easy. Page content can be specified in a number of different formats,
(I tend to use HTML for the regular website and Markdown for blog posts). You edit your page
content then at the command line, type:
$ nanoc compile
That compiles your nanoc source into your final, static web content. You can preview the
build locally and when you're ready, deploy it as you would any static web content, e.g.
using FTP. nanoc has built-in support for rsync so if your server supports it you can deploy
your site without even having to fire up your favourite FTP client. Just add the deploy details
to your site's config (which is written in YAML), for example:
deploy:
default:
dst: "goosoft@goosoftware.co.uk:~/goosoftware.co.uk"
Then deploy with Rake:
$ rake deploy:rsync
## Case study: the Goo Software portfolio
Have a look on the [Goo front page][goo] and you'll see our funky portfolio showing some of the
cool apps we've worked on recently. Have a look at the page source and you'll see it's basically
a load of divs with the same internal structure, one for each app. And that static HTML is exactly
how we used to code it - copying and pasting the div each time we added a new app.
Here's how we achieve the same thing using nanoc. In the config for the index page, we've got this:
-<script src="http://gist.github.com/636322.js?file=index.yaml"></script>
+ apps:
+ - name: RSA Vision
+ slogan: Enlightenment to go
+ itunes_url: http://itunes.apple.com/gb/app/rsa-vision/id397348011?mt=8
+ image: /images/apps/rsa-vision.png
+ description:
+ - > The RSA Vision app brings to you the latest videos from the
+ RSA's free public events programme. You can browse by category,
+ search for videos and compile a playlist of your favourite
+ videos to watch later.
+ - (Check out the RSAnimate category - they're <em>really</em> great!)
+ client: <a href="http://www.torchbox.com/">Torchbox Ltd</a>
+ platform: iPhone and iPod Touch
+
+ - name: iBreastCheck
+ slogan: Helping you to be breast aware
+ itunes_url: http://itunes.apple.com/gb/app/ibreastcheck/id391746205?mt=8
+ image: /images/apps/ibreastcheck.png
+ description:
+ - > iBreastCheck from breast cancer charity Breakthrough helps
+ you to be breast aware with a little TLC: Touch, Look, Check.
+ - > The app has video and slideshow content explaining how to
+ check your breasts, a reminder service to help you to remember
+ to check regularly, and more.
+ client: <a href="http://www.torchbox.com/">Torchbox Ltd</a>
+ platform: iPhone and iPod Touch
Then in the HTML, we've got this:
-<script src="http://gist.github.com/636326.js?file=index.rhtml"></script>
+ <% for app in @item[:apps]%>
+ <div class="app" id="<%= app[:name].downcase.gsub(' ','-') %>">
+ <h2>
+ <a href="<%= app[:itunes_link] %>"><%= app[:name] %></a>
+ <span class="appslogan"><%= app[:slogan]%></span>
+ </h2>
+ <a href="<%= app[:itunes_link] %>">
+ <img src="<%= app[:image] %>" class="screenshot" alt="app screenshot" border="0">
+ </a>
+ <div class="description">
+ <% for desc in app[:description]%>
+ <p><%= desc %></p>
+ <% end %>
+
+ <div class="appstore-badge">
+ <a href="<%= app[:itunes_link] %>">
+ <img src="/images/app-store-badge-clipped.png" alt="App Store Badge Clipped" border="0">
+ </a>
+ </div>
+ <% if app[:client] %>
+ <div class="detail">Client: <%= app[:client] %></div>
+ <% end %>
+ <% if app[:platform] %>
+ <div class="detail">Platform: <%= app[:platform] %></div>
+ <% end %>
+ </div>
+ <div class="app-end"></div>
+ </div>
+ <% end %>
If you're interested in using nanoc yourself and you're the sort of person who learns best
by example, you can find the complete source for this site (including the blog)
[on GitHub][goo-on-github].
[django]: http://www.djangoproject.com/
[nanoc]: http://nanoc.stoneship.org/
[goo-on-github]: http://github.com/simonwhitaker/goo-website
[goo]: http://www.goosoftware.co.uk/
\ No newline at end of file
diff --git a/src/content/blog/0009-Xcode4-symbolication-problems.md b/src/content/blog/0009-Xcode4-symbolication-problems.md
index 91c43cf..2117546 100644
--- a/src/content/blog/0009-Xcode4-symbolication-problems.md
+++ b/src/content/blog/0009-Xcode4-symbolication-problems.md
@@ -1,51 +1,51 @@
---
kind: article
created_at: 2011-03-30
title: The symbolicator helps those who help themselves
---
It sounds like [I'm not the only one][so1] having problems with Xcode 4 not
symbolicating crash logs correctly. Here's the symptom: I drag crash logs that
testers email me into Xcode 4's organiser, then sit and wait for symbolication to
complete. But once it's done, my logs aren't symbolicated - they still just show
a load of memory locations.
Running the symbolicator at the command line sheds a bit of light on what's going
wrong:
$ /Developer/Platforms/iPhoneOS.platform/Developer/Library/PrivateFrameworks\
> /DTDeviceKit.framework/Versions/A/Resources/symbolicatecrash MyApp_etc.crash
Here's the output I get:
Can't understand the output from otool ( -> '\/Developer\/Platforms\/
iPhoneOS\.platform\/Developer\/usr\/bin\/otool -arch armv7 -l
/Users/simon/Library/Developer/Xcode/DerivedData/MyApp-fbxifqioardhgxaitjdftgoejjzz/
Build/Products/Debug-iphonesimulator/MyApp.app/MyApp') at
/Developer/Platforms/iPhoneOS.platform/Developer/Library/PrivateFrameworks/
DTDeviceKit.framework/Versions/A/Resources/symbolicatecrash line 323.
Hmm... Notice that path to the app?
**~/Library/Developer/Xcode/​DerivedData/MyApp-fbxifqioardhgxaitjdftgoejjzz/​Build/Products/Debug-iphonesimulator/​MyApp.app/MyApp**
That's not the right app file - it's the build output from a Debug build, not an
AdHoc build, and worse it's a Debug build for the iOS simulator.
As you may know, the symbolicator uses Spotlight to find the .app file (and the .dSYM file)
it uses to symbolicate a log. And that means that there's a really simple fix.
Adding **~/Library/Developer/Xcode/DerivedData/** to the list
of directories that Spotlight doesn't index makes those build artefacts invisible to
Spotlight, and hence the symbolicator. Just open System Preferences, click on
Spotlight, switch to the Privacy tab and add that DerivedData folder to the list.
You may now find that the symbolicator has a similar problem with apps installed on
the iPhone simulator itself. Adding **~/Library/Application Support/iPhone Simulator/** to
Spotlight's ignore list nails that one.
-<img class="framed" title="Spotlight settings" src="/images/blog/spotlight-symbolicator.png" alt="" />
+<img title="Spotlight settings" src="/images/blog/spotlight-symbolicator.png" alt="" />
Now when I run the symbolicator at the command line, I get properly symbolicated
output, just as expected.
[so1]: http://stackoverflow.com/questions/5458573/xcode-4-failure-to-symbolicate-crash-log/5491334#5491334
\ No newline at end of file
diff --git a/src/content/css/base.css b/src/content/css/base.css
index 6c2aef1..717434b 100644
--- a/src/content/css/base.css
+++ b/src/content/css/base.css
@@ -1,131 +1,108 @@
p, div, span, td, th, li {
line-height: 1.3em;
}
body {
font-family: Helvetica, Arial, sans-serif;
margin: 0 auto;
background-color: #aaa;
}
p {
line-height: 1.4em;
}
h1 {
font-size: 22px;
font-weight: normal;
}
h2 {
font-size: 17px;
}
h3 {
font-size: 13px;
}
h1, h2, h3 {
font-family: "Century Gothic", "Helvetica Neue", Helvetica, Arial, sans-serif;
}
h1 {
}
a[href] {
color: #667200;
}
a:visited {
color: #3C4200;
}
-#main {
- padding: 0;
- margin: 20px 0 30px 0;
- background-color: white;
- position: relative;
- -moz-box-shadow: 0 4px 8px #333;
- -webkit-box-shadow: 0 4px 8px #333;
- box-shadow: 0 4px 8px #333;
-}
-
/* Common bits and bobs
----------------------------------------*/
p img.icon[height="16"] {
vertical-align: -2px;
margin-right: 3px;
}
/* Header
----------------------------------------*/
#header {
position: relative;
height: 180px;
}
#logo {
position: absolute;
left: 40px;
top: 40px;
}
#slogan {
position: absolute;
font-size: 17px;
left: 130px;
top: 140px;
font-family: "Century Gothic", "Helevica Neue", Arial, Helvetica, sans-serif;
color: #09f;
}
/* Tabs
----------------------------------------*/
ul.tabs li {
list-style-type: none;
}
/* Content
----------------------------------------*/
#content {
color: #333;
padding: 0 30px 20px 30px;
}
img.framed {
border: 1px solid #ccc;
padding: 3px;
margin: 8px;
}
/* Footer
----------------------------------------*/
#footer {
padding: 20px 30px;
clear: left;
color: #888;
background-color: #f0f0f0;
border-top: 1px solid #ddd;
font-size: 11px;
text-shadow: #fff 0 1px 1px;
}
-/* Code
-----------------------------------------*/
-
-pre, code {
- font-family: 'Bitstream Vera Sans Mono', Courier, monospace;
- font-size: 12px;
-}
-
-pre {
- padding: 3px;
- background-color: #e0e8f0;
- border: 1px solid #ccc;
-}
diff --git a/src/content/css/blog.css b/src/content/css/blog.css
index d3d8453..afaf79b 100644
--- a/src/content/css/blog.css
+++ b/src/content/css/blog.css
@@ -1,220 +1,239 @@
@import url('base.css');
body {
+ background-color: #000;
max-width: 1200px;
}
#header {
- border-bottom: 1px solid #ddd;
+ border-bottom: 1px solid #444;
}
#content {
+ background-color: #000;
margin-right: 220px;
+ color: #999;
+}
+
+#slogan {
+ color: #666;
+}
+
+/* Code
+----------------------------------------*/
+
+pre, code {
+ font-family: 'Bitstream Vera Sans Mono', Courier, monospace;
+ font-size: 14px;
+ color: #fff;
+}
+
+pre {
+ margin: 30px;
+ padding: 12px;
+ background-color: #333;
+ border-radius: 12px;
}
/* Monochrome nav */
#nav {
top: 20px;
}
#nav .tabs li a {
background-color: #aaa;
color: white;
}
#nav .tabs li a:hover {
background-color: #555;
color: white;
}
#nav .tabs li a.selected {
background-color: #08d;
}
/* Blog article navigation */
.blog-nav {
margin: 12px 0;
font-size: 13px;
}
.blog-nav .nav {
padding: 0;
margin: 0;
}
.blog-nav .nav+.nav {
- border-left: 1px dotted #aaa;
+ border-left: 1px dotted #444;
padding-left: 10px;
margin-left: 10px;
}
/* Misc blog formatting */
h1 {
+ color: #09f;
font-size: 33px;
line-height: 1.1em;
}
.meta {
color: #666;
font-style: italic;
}
blockquote {
- border-left: 2px solid #08d;
- padding-left: 20px;
- margin-left: 20px;
- color: #08d;
+ margin: 30px;
+ padding: 20px 20px 20px 70px;
+ background-color: #333;
+ border-radius: 12px;
+ color: #ccc;
+ background-image: url(../images/open-quote.png);
+ background-repeat: no-repeat;
}
a[href] {
color: #08d;
}
-a[href]:visited {
- color: #333;
-}
-
/* Comments */
.comments {
margin-top: 30px;
padding-top: 15px;
border-top: 1px dashed #777;
}
/* Latest posts */
#sidebar {
float: right;
width: 200px;
padding: 20px 10px;
margin: 0;
font-size: 13px;
- text-align: right;
- border-left: 1px solid #ddd;
}
#sidebar a {
- color: #333;
+ color: #bbb;
}
#sidebar a:hover {
color: #09f;
}
#sidebar .subscribe a {
background-image: url("/images/feed-icon-14x14.png");
background-position: right 0;
background-repeat: no-repeat;
padding-right: 17px;
}
#sidebar h2 {
color: #999;
font-size: 20px;
text-transform: uppercase;
padding: 0;
}
#sidebar ul {
margin: 0;
padding: 0;
}
#sidebar li {
display: block;
padding: 0;
}
#sidebar li a {
display: block;
padding: 5px 0;
}
#sidebar li a.selected {
font-weight: bold;
}
-/* Gist formatting */
- .gist {
- font-size: 13px;
+img.framed {
+ border-color: #666;
}
#footer {
clear: both;
}
@media screen and (max-device-width: 480px) {
body {
width: 480px;
margin: 0;
padding: 0;
- background-color: #fff;
background-image: none;
}
code {
display: block;
max-width: 480px;
overflow: hidden;
}
img {
max-width: 400px;
margin: 6px 0;
padding: 0;
}
img.framed {
border-width: 0;
padding: 0;
margin: 6px 0;
}
#sidebar { display: none; }
p, div, span, li {
font-size: 20px;
}
h1 {
font-size: 28px;
font-weight: normal;
}
h2 {
font-size: 24px;
}
h3 {
font-size: 20px;
}
#header {
height: 160px;
border-width: 0;
}
#main {
margin: 0;
padding: 0;
background-image: none;
-moz-box-shadow: none;
-webkit-box-shadow: none;
box-shadow: none;
}
#logo {
left: 10px;
top: 10px;
}
#content {
clear: both;
padding: 0 20px;
margin: 60px 0 0 0;
width: 440px;
}
}
\ No newline at end of file
diff --git a/src/content/css/goo.css b/src/content/css/goo.css
index 0149fc7..950f87c 100644
--- a/src/content/css/goo.css
+++ b/src/content/css/goo.css
@@ -1,411 +1,422 @@
@import url('base.css');
body {
width: 840px;
}
+#main {
+ padding: 0;
+ margin: 20px 0 30px 0;
+ background-color: white;
+ position: relative;
+ -moz-box-shadow: 0 4px 8px #333;
+ -webkit-box-shadow: 0 4px 8px #333;
+ box-shadow: 0 4px 8px #333;
+}
+
+
/* Header
----------------------------------------*/
#header {
position: relative;
height: 180px;
}
#logo {
position: absolute;
left: 40px;
top: 40px;
}
#slogan {
position: absolute;
font-size: 17px;
left: 130px;
top: 140px;
font-family: "Century Gothic", "Helevica Neue", Arial, Helvetica, sans-serif;
color: #09f;
}
/* Navigation tabs
----------------------------------------*/
#nav {
position: absolute;
right: 0px;
top: 40px;
}
#nav .tabs {
margin: 0;
text-align: right;
}
#nav .tabs li {
margin-bottom: 12px;
}
#nav .tabs li a {
text-decoration: none;
background-color: #A0B400;
color: white;
padding: 5px 10px;
}
#nav .tabs li a:hover {
text-decoration: none;
background-color: #3C4200;
color: white;
padding: 5px 10px;
}
#nav .tabs li a.selected {
background-color: #08d;
}
/* App showcase
----------------------------------------*/
#showcase {
margin: 0;
background-color: black;
background-image: url('../images/app-bg.png');
background-repeat: no-repeat;
color: #ddd;
position: relative;
width: 100%;
}
#apps {
border-left: 1px solid #666;
position: relative;
margin: 0;
width: 689px;
height: 500px;
}
#showcase .detail {
color: #aaa;
font-size: 13px;
}
#showcase a {
color: #fff;
}
.app-end {
clear: left;
}
#showcase .app {
padding: 30px;
}
#showcase .app h2 {
margin-top: 0;
font-size: 22px;
font-weight: bold;
}
#showcase .app h2 a {
text-decoration: none;
color: #eee;
}
#showcase .app h2 a:hover {
text-decoration: underline;
}
#showcase .app h2 .appslogan {
color: #09f;
font-weight: normal;
margin-left: 6px;
}
#showcase .app .screenshot {
float: left;
max-width: 200px;
}
#showcase .app.ipad .screenshot {
float: left;
max-width: 320px;
}
#showcase .app .description {
margin-left: 220px;
padding: 0 15px;
}
#showcase .app.ipad .description {
margin-left: 340px;
padding: 0 15px;
}
#showcase .app .quotation {
font-style: italic;
}
#showcase .app .quotation .source {
font-style: normal;
font-weight: normal;
color: #666;
margin-left: 5px;
}
#showcase .app .install-links {
margin: 0 0 10px 0;
}
#showcase .app .appstore-badge {
padding: 0;
}
#showcase .app div.android-info {
float: right;
width: 220px;
font-size: 12px;
}
#showcase #page_control {
position: relative;
float: left;
height: 100%;
width: 150px;
top: 40px;
left: 0;
height: 100%;
}
#showcase #page_control a {
display: block;
font-size: 15px;
color: white;
padding: 10px 10px;
text-align: left;
text-decoration: none;
border-top: 1px solid #666;
border-bottom: 1px solid #666;
}
#showcase #page_control a.selected {
background-color: black;
}
#showcase #page_control a+a {
border-top-width: 0;
}
#showcase #page_control a:hover {
background-color: #09f;
color: white;
}
/* Contact page
----------------------------------------*/
#contact-details {
margin: 24px 0 12px 40px;
}
#contact-details td {
min-width: 30px;
padding: 0 0 10px 0;
vertical-align: top;
}
#map {
border: 1px solid #ccc;
padding: 4px;
float: right;
}
#end-map {
clear: right;
}
/* Support page
----------------------------------------*/
.support-steps img {
margin: 10px 0 30px 10px;
border: 1px solid #ccc;
padding: 3px;
}
.support-steps li+li {
margin-top: 6px;
}
div.support-item {
border-top: 1px solid #A0B400;
padding-top: 10px;
margin-top: 40px;
}
/* About page
----------------------------------------*/
.portrait {
float: left;
width: 162px;
}
.biog {
margin-left: 180px;
}
/* Blog index
----------------------------------------*/
ul.blog-items {
padding-left: 0;
}
.blog-items li {
list-style-type: none;
line-height: 1.7em;
}
.blog-items li .date {
color: #999;
font-size: 12px;
}
@media screen and (max-device-width: 480px) {
body {
width: 480px;
margin: 0;
padding: 0;
background-color: #fff;
background-image: none;
}
p, div, span, li {
font-size: 20px;
}
h1 {
font-size: 28px;
font-weight: normal;
}
h2 {
font-size: 24px;
}
h3 {
font-size: 20px;
}
#header {
height: 160px;
}
#main {
margin: 0;
padding: 0;
background-image: none;
-moz-box-shadow: none;
-webkit-box-shadow: none;
box-shadow: none;
}
#logo {
left: 10px;
top: 20px;
}
#slogan {
left: 120px;
width: 340px;
top: 120px;
}
#nav {
position: relative;
top: 0;
left: 0;
padding: 0;
margin: 10px 0;
}
#nav .tabs {
text-align: left;
padding: 0;
margin: 0 20px;
}
#nav .tabs li {
float: left;
font-size: 20px;
}
#nav .tabs li+li {
margin-left: 1px;
}
#content {
clear: both;
padding: 0 20px;
margin: 60px 0 0 0;
width: 440px;
}
#showcase {
width: 440px;
background-color: black;
border-radius: 0;
-moz-border-radius: 0;
padding: 0 20px;
margin: 20px 0 0 0;
}
#showcase #apps {
width: 100%;
border-width: 0;
height: auto;
}
#showcase .app h2 a {
}
#showcase .app+.app {
border-top: 1px solid #333;
}
#showcase .app {
margin: 0;
padding: 30px 0px;
}
#showcase .app img.screenshot {
width: 120px;
}
#showcase .app .description {
margin-left: 140px;
padding: 0px;
}
#footer {
margin: 0;
padding: 20px 10px;
text-align: center;
font-size: 10px;
}
#footer a {
}
.portrait {
float: left;
width: 60px;
}
.biog {
margin-left: 80px;
}
}
\ No newline at end of file
diff --git a/src/content/images/open-quote.png b/src/content/images/open-quote.png
new file mode 100644
index 0000000..0f12fda
Binary files /dev/null and b/src/content/images/open-quote.png differ
|
simonwhitaker/goo-website
|
135c847c8b71adcecf471b1a93c03fac7a12f1cd
|
Added Lucky Voice Karaoke to the portfolio
|
diff --git a/src/content/css/goo.css b/src/content/css/goo.css
index 8b35814..0149fc7 100644
--- a/src/content/css/goo.css
+++ b/src/content/css/goo.css
@@ -1,400 +1,411 @@
@import url('base.css');
body {
width: 840px;
}
/* Header
----------------------------------------*/
#header {
position: relative;
height: 180px;
}
#logo {
position: absolute;
left: 40px;
top: 40px;
}
#slogan {
position: absolute;
font-size: 17px;
left: 130px;
top: 140px;
font-family: "Century Gothic", "Helevica Neue", Arial, Helvetica, sans-serif;
color: #09f;
}
/* Navigation tabs
----------------------------------------*/
#nav {
position: absolute;
right: 0px;
top: 40px;
}
#nav .tabs {
margin: 0;
text-align: right;
}
#nav .tabs li {
margin-bottom: 12px;
}
#nav .tabs li a {
text-decoration: none;
background-color: #A0B400;
color: white;
padding: 5px 10px;
}
#nav .tabs li a:hover {
text-decoration: none;
background-color: #3C4200;
color: white;
padding: 5px 10px;
}
#nav .tabs li a.selected {
background-color: #08d;
}
/* App showcase
----------------------------------------*/
#showcase {
margin: 0;
background-color: black;
background-image: url('../images/app-bg.png');
background-repeat: no-repeat;
color: #ddd;
position: relative;
width: 100%;
}
#apps {
border-left: 1px solid #666;
position: relative;
margin: 0;
width: 689px;
height: 500px;
}
#showcase .detail {
color: #aaa;
font-size: 13px;
}
#showcase a {
color: #fff;
}
.app-end {
clear: left;
}
#showcase .app {
padding: 30px;
}
#showcase .app h2 {
margin-top: 0;
font-size: 22px;
font-weight: bold;
}
#showcase .app h2 a {
text-decoration: none;
color: #eee;
}
#showcase .app h2 a:hover {
text-decoration: underline;
}
#showcase .app h2 .appslogan {
color: #09f;
font-weight: normal;
margin-left: 6px;
}
#showcase .app .screenshot {
float: left;
max-width: 200px;
}
+#showcase .app.ipad .screenshot {
+ float: left;
+ max-width: 320px;
+}
+
+
#showcase .app .description {
margin-left: 220px;
padding: 0 15px;
}
+#showcase .app.ipad .description {
+ margin-left: 340px;
+ padding: 0 15px;
+}
+
#showcase .app .quotation {
font-style: italic;
}
#showcase .app .quotation .source {
font-style: normal;
font-weight: normal;
color: #666;
margin-left: 5px;
}
#showcase .app .install-links {
margin: 0 0 10px 0;
}
#showcase .app .appstore-badge {
padding: 0;
}
#showcase .app div.android-info {
float: right;
width: 220px;
font-size: 12px;
}
#showcase #page_control {
position: relative;
float: left;
height: 100%;
width: 150px;
top: 40px;
left: 0;
height: 100%;
}
#showcase #page_control a {
display: block;
font-size: 15px;
color: white;
padding: 10px 10px;
text-align: left;
text-decoration: none;
border-top: 1px solid #666;
border-bottom: 1px solid #666;
}
#showcase #page_control a.selected {
background-color: black;
}
#showcase #page_control a+a {
border-top-width: 0;
}
#showcase #page_control a:hover {
background-color: #09f;
color: white;
}
/* Contact page
----------------------------------------*/
#contact-details {
margin: 24px 0 12px 40px;
}
#contact-details td {
min-width: 30px;
padding: 0 0 10px 0;
vertical-align: top;
}
#map {
border: 1px solid #ccc;
padding: 4px;
float: right;
}
#end-map {
clear: right;
}
/* Support page
----------------------------------------*/
.support-steps img {
margin: 10px 0 30px 10px;
border: 1px solid #ccc;
padding: 3px;
}
.support-steps li+li {
margin-top: 6px;
}
div.support-item {
border-top: 1px solid #A0B400;
padding-top: 10px;
margin-top: 40px;
}
/* About page
----------------------------------------*/
.portrait {
float: left;
width: 162px;
}
.biog {
margin-left: 180px;
}
/* Blog index
----------------------------------------*/
ul.blog-items {
padding-left: 0;
}
.blog-items li {
list-style-type: none;
line-height: 1.7em;
}
.blog-items li .date {
color: #999;
font-size: 12px;
}
@media screen and (max-device-width: 480px) {
body {
width: 480px;
margin: 0;
padding: 0;
background-color: #fff;
background-image: none;
}
p, div, span, li {
font-size: 20px;
}
h1 {
font-size: 28px;
font-weight: normal;
}
h2 {
font-size: 24px;
}
h3 {
font-size: 20px;
}
#header {
height: 160px;
}
#main {
margin: 0;
padding: 0;
background-image: none;
-moz-box-shadow: none;
-webkit-box-shadow: none;
box-shadow: none;
}
#logo {
left: 10px;
top: 20px;
}
#slogan {
left: 120px;
width: 340px;
top: 120px;
}
#nav {
position: relative;
top: 0;
left: 0;
padding: 0;
margin: 10px 0;
}
#nav .tabs {
text-align: left;
padding: 0;
margin: 0 20px;
}
#nav .tabs li {
float: left;
font-size: 20px;
}
#nav .tabs li+li {
margin-left: 1px;
}
#content {
clear: both;
padding: 0 20px;
margin: 60px 0 0 0;
width: 440px;
}
#showcase {
width: 440px;
background-color: black;
border-radius: 0;
-moz-border-radius: 0;
padding: 0 20px;
margin: 20px 0 0 0;
}
#showcase #apps {
width: 100%;
border-width: 0;
height: auto;
}
#showcase .app h2 a {
}
#showcase .app+.app {
border-top: 1px solid #333;
}
#showcase .app {
margin: 0;
padding: 30px 0px;
}
#showcase .app img.screenshot {
width: 120px;
}
#showcase .app .description {
margin-left: 140px;
padding: 0px;
}
#footer {
margin: 0;
padding: 20px 10px;
text-align: center;
font-size: 10px;
}
#footer a {
}
.portrait {
float: left;
width: 60px;
}
.biog {
margin-left: 80px;
}
}
\ No newline at end of file
diff --git a/src/content/images/apps/habilis-logo-white.png b/src/content/images/apps/habilis-logo-white.png
deleted file mode 100644
index e9ca23d..0000000
Binary files a/src/content/images/apps/habilis-logo-white.png and /dev/null differ
diff --git a/src/content/images/apps/habilis-logo.png b/src/content/images/apps/habilis-logo.png
deleted file mode 100644
index df279d0..0000000
Binary files a/src/content/images/apps/habilis-logo.png and /dev/null differ
diff --git a/src/content/images/apps/lucky-voice.png b/src/content/images/apps/lucky-voice.png
new file mode 100644
index 0000000..a651e78
Binary files /dev/null and b/src/content/images/apps/lucky-voice.png differ
diff --git a/src/content/index.rhtml b/src/content/index.rhtml
index d09c87b..8a9416d 100644
--- a/src/content/index.rhtml
+++ b/src/content/index.rhtml
@@ -1,53 +1,53 @@
<div id="content">
<h1>
Welcome to Goo!
</h1>
<p>
We're a UK software house specialising in apps for iPhone, iPad and Android. Here's some of the stuff we've done.
</p>
</div>
<div id="showcase">
<div id="apps">
<% for app in @item[:apps]%>
- <div class="app" id="<%= app[:name].downcase.gsub(' ','-') %>">
+ <div class="app <%= app[:class] %>" id="<%= app[:name].downcase.gsub(' ','-') %>">
<a href="<%= app[:itunes_url] %>"><img src="<%= app[:image] %>" class="screenshot" alt="app screenshot" border="0"></a>
<div class="description">
<h2>
<a href="<%= app[:itunes_url] %>"><%= app[:name] %></a>
<span class="appslogan"<%if app[:slogan_colour]%> style="color:<%=app[:slogan_colour]%>"<%end%>><%= app[:slogan]%></span>
</h2>
<% for desc in app[:description]%>
<p><%= desc %></p>
<% end %>
<div class="install-links">
<% if app[:android_package] %>
<div class="android-info">
To install on Android, search the marketplace for <%= app[:name] %> or scan
<a href="http://chart.apis.google.com/chart?cht=qr&chs=400x400&chld=Q%7C3&chl=market://details?id=<%= app[:android_package] %>">this QR code</a>
</div>
<% end %>
<% if app[:itunes_url] %>
<div class="appstore-badge">
<a href="<%= app[:itunes_url] %>"><img src="/images/app-store-badge-clipped.png" alt="App Store Badge Clipped" border="0"></a>
</div>
<% end %>
</div>
<div style="clear:right"> </div>
<% if app[:client] %>
<div class="detail">Client: <%= app[:client] %></div>
<% end %>
<% if app[:platform] %>
<div class="detail">Platform: <%= app[:platform] %></div>
<% end %>
</div>
<div class="app-end"></div>
</div>
<% end %>
</div><!-- #apps -->
</div><!-- #showcase -->
diff --git a/src/content/index.yaml b/src/content/index.yaml
index 796d21b..4e7c0e0 100644
--- a/src/content/index.yaml
+++ b/src/content/index.yaml
@@ -1,86 +1,99 @@
title: "Fantastic Apps for iPhone, iPad and Android"
description: "Goo Software Ltd is an independent UK-based software house specialising in development of apps for iPhone, iPad and Android."
js_imports:
- showcase.js
apps:
+ - name: Lucky Voice
+ slogan: Sing your heart out!
+ slogan_colour: "#FE01B4"
+ itunes_url: http://itunes.apple.com/gb/app/lucky-voice-karaoke/id428963272?mt=8
+ image: /images/apps/lucky-voice.png
+ description:
+ - > The ultimate karaoke experience for your iPad!
+ - > Sing along to over 7,500 songs
+ client: Lucky Voice Ltd
+ platform: iPad
+ class: ipad
+
- name: BBC Bitesize Exam Alert
slogan: Track your exams the fun way
slogan_colour: "#39f"
itunes_url: http://itunes.apple.com/gb/app/gcse-bitesize-exam-alert/id414023535?mt=8
image: /images/apps/bbc-bitesize.png
description:
- > Our popular Exam Countdown app, re-branded
for the BBC Bitesize iPhone app series.
- > Track your forthcoming exams, get study tips
and share with your friends via Facebook
client: BBC Bitesize / Pearson Education Ltd
platform: iPhone and iPod Touch
- name: The xx
slogan: Innovative video experience
+ slogan_colour: "#4e6072"
itunes_url: http://itunes.apple.com/gb/app/the-xx/id394653020?mt=8
image: /images/apps/the-xx.png
description:
- > Using this fun and unique app, you and up to two friends can
play tracks from the xx's award-winning debut album <em>XX</em>
across multiple iPhones or iPod Touches.
- > <span class="quotation">
"An ingenious use of technology"
<span class="source"> — The Guardian</span>
</span>
client: Beggars Group Ltd
platform: iPhone and iPod Touch
- name: RSA Vision
slogan: Enlightenment to go
slogan_colour: "#CE5B02"
itunes_url: http://itunes.apple.com/gb/app/rsa-vision/id397348011?mt=8
android_package: com.goocode.rsavision
image: /images/apps/rsa-vision.png
description:
- > The RSA Vision app brings to you the latest videos from the
RSA's free public events programme. You can browse by category,
search for videos and compile a playlist of your favourite
videos to watch later.
- (Check out the RSAnimate category - they're <em>really</em> great!)
client: <a href="http://www.torchbox.com/">Torchbox Ltd</a>
platform: "iPhone, iPod Touch, Android"
- name: iBreastCheck
slogan: Helping you to be breast aware
slogan_colour: "#C70064"
itunes_url: http://itunes.apple.com/gb/app/ibreastcheck/id391746205?mt=8
image: /images/apps/ibreastcheck.png
description:
- > iBreastCheck from breast cancer charity Breakthrough helps
you to be breast aware with a little TLC: Touch, Look, Check.
- > The app has video and slideshow content explaining how to
check your breasts, a reminder service to help you to remember
to check regularly, and more.
client: <a href="http://www.torchbox.com/">Torchbox Ltd</a>
platform: iPhone and iPod Touch
- name: Exam Countdown
slogan: Track your exams the fun way
slogan_colour: "#888"
itunes_url: http://itunes.apple.com/gb/app/exam-countdown/id372962356?mt=8
image: /images/apps/exam-countdown.png
description:
- > The Exam Countdown app allows students to keep track of
forthcoming exams and share their thoughts via Facebook.
client: Pearson Education Ltd
platform: iPhone and iPod Touch
- name: Sports Massager
itunes_url: http://itunes.apple.com/gb/app/sports-massager/id352993865?mt=8
slogan: Let your phone take the strain
slogan_colour: "#3956BD"
image: /images/apps/sports-massager.png
description:
- > Aching after a great workout? Let Dan The Man take the strain!
Just hit the button then enjoy a relaxing massage from Dan The
Man in this fun app - Goo's first foray onto the App Store.
platform: iPhone
|
simonwhitaker/goo-website
|
52cf560f65156d8ab93890e291794d401f13879f
|
New blog post
|
diff --git a/src/content/blog/0009-Xcode4-symbolication-problems.md b/src/content/blog/0009-Xcode4-symbolication-problems.md
index cc6f83a..91c43cf 100644
--- a/src/content/blog/0009-Xcode4-symbolication-problems.md
+++ b/src/content/blog/0009-Xcode4-symbolication-problems.md
@@ -1,51 +1,51 @@
---
kind: article
created_at: 2011-03-30
title: The symbolicator helps those who help themselves
---
It sounds like [I'm not the only one][so1] having problems with Xcode 4 not
symbolicating crash logs correctly. Here's the symptom: I drag crash logs that
testers email me into Xcode 4's organiser, then sit and wait for symbolication to
complete. But once it's done, my logs aren't symbolicated - they still just show
a load of memory locations.
Running the symbolicator at the command line sheds a bit of light on what's going
wrong:
$ /Developer/Platforms/iPhoneOS.platform/Developer/Library/PrivateFrameworks\
> /DTDeviceKit.framework/Versions/A/Resources/symbolicatecrash MyApp_etc.crash
Here's the output I get:
Can't understand the output from otool ( -> '\/Developer\/Platforms\/
iPhoneOS\.platform\/Developer\/usr\/bin\/otool -arch armv7 -l
/Users/simon/Library/Developer/Xcode/DerivedData/MyApp-fbxifqioardhgxaitjdftgoejjzz/
Build/Products/Debug-iphonesimulator/MyApp.app/MyApp') at
/Developer/Platforms/iPhoneOS.platform/Developer/Library/PrivateFrameworks/
DTDeviceKit.framework/Versions/A/Resources/symbolicatecrash line 323.
Hmm... Notice that path to the app?
-**~/Library/Developer/Xcode/DerivedData/MyApp-fbxifqioardhgxaitjdftgoejjzz/Build/Products/Debug-iphonesimulator/MyApp.app/MyApp**
+**~/Library/Developer/Xcode/​DerivedData/MyApp-fbxifqioardhgxaitjdftgoejjzz/​Build/Products/Debug-iphonesimulator/​MyApp.app/MyApp**
That's not the right app file - it's the build output from a Debug build, not an
AdHoc build, and worse it's a Debug build for the iOS simulator.
As you may know, the symbolicator uses Spotlight to find the .app file (and the .dSYM file)
it uses to symbolicate a log. And that means that there's a really simple fix.
Adding **~/Library/Developer/Xcode/DerivedData/** to the list
of directories that Spotlight doesn't index makes those build artefacts invisible to
-Spotlight, and hence the symbolicator. Just open System Preferences, click on
+Spotlight, and hence the symbolicator. Just open System Preferences, click on
Spotlight, switch to the Privacy tab and add that DerivedData folder to the list.
You may now find that the symbolicator has a similar problem with apps installed on
the iPhone simulator itself. Adding **~/Library/Application Support/iPhone Simulator/** to
Spotlight's ignore list nails that one.
-<img class="framed" width="600" title="Spotlight settings" src="/images/blog/spotlight-symbolicator.png" alt="" />
+<img class="framed" title="Spotlight settings" src="/images/blog/spotlight-symbolicator.png" alt="" />
Now when I run the symbolicator at the command line, I get properly symbolicated
output, just as expected.
[so1]: http://stackoverflow.com/questions/5458573/xcode-4-failure-to-symbolicate-crash-log/5491334#5491334
\ No newline at end of file
diff --git a/src/content/css/blog.css b/src/content/css/blog.css
index 5c456e7..d3d8453 100644
--- a/src/content/css/blog.css
+++ b/src/content/css/blog.css
@@ -1,146 +1,220 @@
@import url('base.css');
body {
max-width: 1200px;
}
#header {
border-bottom: 1px solid #ddd;
}
#content {
margin-right: 220px;
}
/* Monochrome nav */
#nav {
top: 20px;
}
#nav .tabs li a {
background-color: #aaa;
color: white;
}
#nav .tabs li a:hover {
background-color: #555;
color: white;
}
#nav .tabs li a.selected {
background-color: #08d;
}
/* Blog article navigation */
.blog-nav {
margin: 12px 0;
font-size: 13px;
}
.blog-nav .nav {
padding: 0;
margin: 0;
}
.blog-nav .nav+.nav {
border-left: 1px dotted #aaa;
padding-left: 10px;
margin-left: 10px;
}
/* Misc blog formatting */
h1 {
font-size: 33px;
line-height: 1.1em;
}
.meta {
color: #666;
font-style: italic;
}
blockquote {
border-left: 2px solid #08d;
padding-left: 20px;
margin-left: 20px;
color: #08d;
}
a[href] {
color: #08d;
}
a[href]:visited {
color: #333;
}
/* Comments */
.comments {
margin-top: 30px;
padding-top: 15px;
border-top: 1px dashed #777;
}
/* Latest posts */
#sidebar {
float: right;
width: 200px;
padding: 20px 10px;
margin: 0;
font-size: 13px;
text-align: right;
border-left: 1px solid #ddd;
}
#sidebar a {
color: #333;
}
#sidebar a:hover {
color: #09f;
}
#sidebar .subscribe a {
background-image: url("/images/feed-icon-14x14.png");
background-position: right 0;
background-repeat: no-repeat;
padding-right: 17px;
}
#sidebar h2 {
color: #999;
font-size: 20px;
text-transform: uppercase;
padding: 0;
}
#sidebar ul {
margin: 0;
padding: 0;
}
#sidebar li {
display: block;
padding: 0;
}
#sidebar li a {
display: block;
padding: 5px 0;
}
#sidebar li a.selected {
font-weight: bold;
}
/* Gist formatting */
.gist {
font-size: 13px;
}
#footer {
clear: both;
+}
+
+@media screen and (max-device-width: 480px) {
+ body {
+ width: 480px;
+ margin: 0;
+ padding: 0;
+ background-color: #fff;
+ background-image: none;
+ }
+
+ code {
+ display: block;
+ max-width: 480px;
+ overflow: hidden;
+ }
+
+ img {
+ max-width: 400px;
+ margin: 6px 0;
+ padding: 0;
+ }
+
+ img.framed {
+ border-width: 0;
+ padding: 0;
+ margin: 6px 0;
+
+ }
+
+ #sidebar { display: none; }
+
+ p, div, span, li {
+ font-size: 20px;
+ }
+
+ h1 {
+ font-size: 28px;
+ font-weight: normal;
+ }
+
+ h2 {
+ font-size: 24px;
+ }
+
+ h3 {
+ font-size: 20px;
+ }
+
+ #header {
+ height: 160px;
+ border-width: 0;
+ }
+
+ #main {
+ margin: 0;
+ padding: 0;
+ background-image: none;
+ -moz-box-shadow: none;
+ -webkit-box-shadow: none;
+ box-shadow: none;
+ }
+
+ #logo {
+ left: 10px;
+ top: 10px;
+ }
+
+ #content {
+ clear: both;
+ padding: 0 20px;
+ margin: 60px 0 0 0;
+ width: 440px;
+ }
}
\ No newline at end of file
diff --git a/src/content/images/blog/spotlight-symbolicator.png b/src/content/images/blog/spotlight-symbolicator.png
index 8904bfd..46ef7d8 100644
Binary files a/src/content/images/blog/spotlight-symbolicator.png and b/src/content/images/blog/spotlight-symbolicator.png differ
|
simonwhitaker/goo-website
|
223ec9d3c2b751b9603c3b8c914169bbeebeb0a4
|
Fix missing space at end of line
|
diff --git a/src/content/index.yaml b/src/content/index.yaml
index 328cdf2..796d21b 100644
--- a/src/content/index.yaml
+++ b/src/content/index.yaml
@@ -1,86 +1,86 @@
title: "Fantastic Apps for iPhone, iPad and Android"
description: "Goo Software Ltd is an independent UK-based software house specialising in development of apps for iPhone, iPad and Android."
js_imports:
- showcase.js
apps:
- name: BBC Bitesize Exam Alert
slogan: Track your exams the fun way
slogan_colour: "#39f"
itunes_url: http://itunes.apple.com/gb/app/gcse-bitesize-exam-alert/id414023535?mt=8
image: /images/apps/bbc-bitesize.png
description:
- > Our popular Exam Countdown app, re-branded
for the BBC Bitesize iPhone app series.
- - > Track your forthcoming exams, get study tips
+ - > Track your forthcoming exams, get study tips
and share with your friends via Facebook
client: BBC Bitesize / Pearson Education Ltd
platform: iPhone and iPod Touch
- name: The xx
slogan: Innovative video experience
itunes_url: http://itunes.apple.com/gb/app/the-xx/id394653020?mt=8
image: /images/apps/the-xx.png
description:
- > Using this fun and unique app, you and up to two friends can
play tracks from the xx's award-winning debut album <em>XX</em>
across multiple iPhones or iPod Touches.
- > <span class="quotation">
"An ingenious use of technology"
<span class="source"> — The Guardian</span>
</span>
client: Beggars Group Ltd
platform: iPhone and iPod Touch
- name: RSA Vision
slogan: Enlightenment to go
slogan_colour: "#CE5B02"
itunes_url: http://itunes.apple.com/gb/app/rsa-vision/id397348011?mt=8
android_package: com.goocode.rsavision
image: /images/apps/rsa-vision.png
description:
- > The RSA Vision app brings to you the latest videos from the
RSA's free public events programme. You can browse by category,
search for videos and compile a playlist of your favourite
videos to watch later.
- (Check out the RSAnimate category - they're <em>really</em> great!)
client: <a href="http://www.torchbox.com/">Torchbox Ltd</a>
platform: "iPhone, iPod Touch, Android"
- name: iBreastCheck
slogan: Helping you to be breast aware
slogan_colour: "#C70064"
itunes_url: http://itunes.apple.com/gb/app/ibreastcheck/id391746205?mt=8
image: /images/apps/ibreastcheck.png
description:
- > iBreastCheck from breast cancer charity Breakthrough helps
you to be breast aware with a little TLC: Touch, Look, Check.
- > The app has video and slideshow content explaining how to
check your breasts, a reminder service to help you to remember
to check regularly, and more.
client: <a href="http://www.torchbox.com/">Torchbox Ltd</a>
platform: iPhone and iPod Touch
- name: Exam Countdown
slogan: Track your exams the fun way
slogan_colour: "#888"
itunes_url: http://itunes.apple.com/gb/app/exam-countdown/id372962356?mt=8
image: /images/apps/exam-countdown.png
description:
- > The Exam Countdown app allows students to keep track of
forthcoming exams and share their thoughts via Facebook.
client: Pearson Education Ltd
platform: iPhone and iPod Touch
- name: Sports Massager
itunes_url: http://itunes.apple.com/gb/app/sports-massager/id352993865?mt=8
slogan: Let your phone take the strain
slogan_colour: "#3956BD"
image: /images/apps/sports-massager.png
description:
- > Aching after a great workout? Let Dan The Man take the strain!
Just hit the button then enjoy a relaxing massage from Dan The
Man in this fun app - Goo's first foray onto the App Store.
platform: iPhone
|
simonwhitaker/goo-website
|
d1047ddf6eddc041502eac2f5de41d109e90467f
|
New blog post
|
diff --git a/src/content/blog/0009-Xcode4-symbolication-problems.md b/src/content/blog/0009-Xcode4-symbolication-problems.md
new file mode 100644
index 0000000..cc6f83a
--- /dev/null
+++ b/src/content/blog/0009-Xcode4-symbolication-problems.md
@@ -0,0 +1,51 @@
+---
+kind: article
+created_at: 2011-03-30
+title: The symbolicator helps those who help themselves
+---
+
+It sounds like [I'm not the only one][so1] having problems with Xcode 4 not
+symbolicating crash logs correctly. Here's the symptom: I drag crash logs that
+testers email me into Xcode 4's organiser, then sit and wait for symbolication to
+complete. But once it's done, my logs aren't symbolicated - they still just show
+a load of memory locations.
+
+Running the symbolicator at the command line sheds a bit of light on what's going
+wrong:
+
+ $ /Developer/Platforms/iPhoneOS.platform/Developer/Library/PrivateFrameworks\
+ > /DTDeviceKit.framework/Versions/A/Resources/symbolicatecrash MyApp_etc.crash
+
+Here's the output I get:
+
+ Can't understand the output from otool ( -> '\/Developer\/Platforms\/
+ iPhoneOS\.platform\/Developer\/usr\/bin\/otool -arch armv7 -l
+ /Users/simon/Library/Developer/Xcode/DerivedData/MyApp-fbxifqioardhgxaitjdftgoejjzz/
+ Build/Products/Debug-iphonesimulator/MyApp.app/MyApp') at
+ /Developer/Platforms/iPhoneOS.platform/Developer/Library/PrivateFrameworks/
+ DTDeviceKit.framework/Versions/A/Resources/symbolicatecrash line 323.
+
+Hmm... Notice that path to the app?
+
+**~/Library/Developer/Xcode/DerivedData/MyApp-fbxifqioardhgxaitjdftgoejjzz/Build/Products/Debug-iphonesimulator/MyApp.app/MyApp**
+
+That's not the right app file - it's the build output from a Debug build, not an
+AdHoc build, and worse it's a Debug build for the iOS simulator.
+
+As you may know, the symbolicator uses Spotlight to find the .app file (and the .dSYM file)
+it uses to symbolicate a log. And that means that there's a really simple fix.
+Adding **~/Library/Developer/Xcode/DerivedData/** to the list
+of directories that Spotlight doesn't index makes those build artefacts invisible to
+Spotlight, and hence the symbolicator. Just open System Preferences, click on
+Spotlight, switch to the Privacy tab and add that DerivedData folder to the list.
+
+You may now find that the symbolicator has a similar problem with apps installed on
+the iPhone simulator itself. Adding **~/Library/Application Support/iPhone Simulator/** to
+Spotlight's ignore list nails that one.
+
+<img class="framed" width="600" title="Spotlight settings" src="/images/blog/spotlight-symbolicator.png" alt="" />
+
+Now when I run the symbolicator at the command line, I get properly symbolicated
+output, just as expected.
+
+[so1]: http://stackoverflow.com/questions/5458573/xcode-4-failure-to-symbolicate-crash-log/5491334#5491334
\ No newline at end of file
diff --git a/src/content/images/blog/spotlight-symbolicator.png b/src/content/images/blog/spotlight-symbolicator.png
new file mode 100644
index 0000000..8904bfd
Binary files /dev/null and b/src/content/images/blog/spotlight-symbolicator.png differ
|
simonwhitaker/goo-website
|
3150bf74afb5f1f9f6dad6dd97e6c25869cb0cb8
|
Add BBC Bitesize exam alert app
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..249e7ef
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,4 @@
+.DS_Store
+src/tmp/
+html
+artwork/Goo product compositions/
diff --git a/README.markdown b/README.markdown
new file mode 100644
index 0000000..c8e7bab
--- /dev/null
+++ b/README.markdown
@@ -0,0 +1,3 @@
+This is the code base for the Goo Software Ltd website ([www.goosoftware.co.uk](http://www.goosoftware.co.uk)).
+
+It uses [Nanoc](http://nanoc.stoneship.org/) to build the static site contents - check it out, it's really cool.
\ No newline at end of file
diff --git a/artwork/Habilis logo.opacity b/artwork/Habilis logo.opacity
new file mode 100644
index 0000000..c396325
Binary files /dev/null and b/artwork/Habilis logo.opacity differ
diff --git a/artwork/app-bg.psd b/artwork/app-bg.psd
new file mode 100644
index 0000000..f5f678c
Binary files /dev/null and b/artwork/app-bg.psd differ
diff --git a/src/Rakefile b/src/Rakefile
new file mode 100644
index 0000000..99ccfe6
--- /dev/null
+++ b/src/Rakefile
@@ -0,0 +1,11 @@
+require 'nanoc3/tasks'
+
+desc "Compiles the static site contents using nanoc"
+task :compile do |t|
+ sh "nanoc compile"
+end
+
+task :default => [:compile]
+
+desc "Builds and deploys to goosoftware.co.uk"
+task :deploy => [:compile, 'deploy:rsync']
\ No newline at end of file
diff --git a/src/Rules b/src/Rules
new file mode 100644
index 0000000..f59a169
--- /dev/null
+++ b/src/Rules
@@ -0,0 +1,61 @@
+#!/usr/bin/env ruby
+
+# A few helpful tips about the Rules file:
+#
+# * The order of rules is important: for each item, only the first matching
+# rule is applied.
+#
+# * Item identifiers start and end with a slash (e.g. â/about/â for the file
+# âcontent/about.htmlâ). To select all children, grandchildren, ⦠of an
+# item, use the pattern â/about/*/â; â/about/*â will also select the parent,
+# because â*â matches zero or more characters.
+
+compile '/blog/feed/' do
+ filter :erb
+end
+
+compile '*' do
+ do_layout = false
+
+ if item[:extension] =~ /(md|markdown)/
+ filter :kramdown
+ do_layout = true
+ elsif item[:extension] =~ /r?html/
+ filter :erb
+ do_layout = true
+ end
+
+ if do_layout then
+ if item[:kind] == 'article' or item[:kind] == 'draft'
+ layout 'blog'
+ else
+ layout 'goo'
+ end
+ end
+end
+
+route '/blog/feed/' do
+ '/blog.xml'
+end
+
+route %r{^/(css|js|images)/.*/} do
+ item.identifier.chop + '.' + item[:extension]
+end
+
+route '/error/*/' do
+ item.identifier.chop + '.html'
+end
+
+route '/htaccess/' do
+ '/.htaccess'
+end
+
+route '/blog/*/' do
+ '/blog/' + item[:title].to_slug + '/index.html'
+end
+
+route '*' do
+ item.identifier + 'index.html'
+end
+
+layout '*', :erb
diff --git a/src/config.yaml b/src/config.yaml
new file mode 100644
index 0000000..7657989
--- /dev/null
+++ b/src/config.yaml
@@ -0,0 +1,51 @@
+# A list of file extensions that nanoc will consider to be textual rather than
+# binary. If an item with an extension not in this list is found, the file
+# will be considered as binary.
+text_extensions: [ 'css', 'html', 'js', 'markdown', 'md', 'rb', 'txt', 'xhtml', 'xml', 'rhtml' ]
+
+# The path to the directory where all generated files will be written to. This
+# can be an absolute path starting with a slash, but it can also be path
+# relative to the site directory.
+output_dir: ../html
+
+# A list of index filenames, i.e. names of files that will be served by a web
+# server when a directory is requested. Usually, index files are named
+# âindex.hmlâ, but depending on the web server, this may be something else,
+# such as âdefault.htmâ. This list is used by nanoc to generate pretty URLs.
+index_filenames: [ 'index.html' ]
+
+# Whether or not to generate a diff of the compiled content when compiling a
+# site. The diff will contain the differences between the compiled content
+# before and after the last site compilation.
+enable_output_diff: false
+
+# The data sources where nanoc loads its data from. This is an array of
+# hashes; each array element represents a single data source. By default,
+# there is only a single data source that reads data from the âcontent/â and
+# âlayout/â directories in the site directory.
+data_sources:
+ -
+ # The type is the identifier of the data source. By default, this will be
+ # `filesystem_unified`.
+ type: filesystem_unified
+
+ # The path where items should be mounted (comparable to mount points in
+ # Unix-like systems). This is â/â by default, meaning that items will have
+ # â/â prefixed to their identifiers. If the items root were â/en/â
+ # instead, an item at content/about.html would have an identifier of
+ # â/en/about/â instead of just â/about/â.
+ items_root: /
+
+ # The path where layouts should be mounted. The layouts root behaves the
+ # same as the items root, but applies to layouts rather than items.
+ layouts_root: /
+
+deploy:
+ default:
+ dst: "goosoft@goosoftware.co.uk:~/goosoftware.co.uk"
+
+base_url: http://www.goosoftware.co.uk
+
+title: Goo Software Ltd
+author_name: Simon Whitaker
+author_uri: http://www.goosoftware.co.uk/about/
\ No newline at end of file
diff --git a/src/content/about.rhtml b/src/content/about.rhtml
new file mode 100644
index 0000000..cc295d7
--- /dev/null
+++ b/src/content/about.rhtml
@@ -0,0 +1,21 @@
+<div id="content">
+ <h1>
+ About Goo
+ </h1>
+ <img src="/images/simon.jpg" class="portrait" width="162" alt="Simon Whitaker">
+ <div class="biog">
+ <p>
+ Goo Software Ltd is the creative brainchild of Simon Whitaker.
+ </p>
+ <p>
+ Simon has a strong background in software development, having worked for a range of different companies, writing everything from embedded firmware that he debugged with an oscilloscope to distributed processing systems running on fleets of hardware spread across a continent.
+ </p>
+ <p>
+ In 2010, Simon left his job as a Software Development Manager for Amazon.com to set up Goo Software Ltd. Simon prides himself on his great combination of top notch technical skills and an ability to speak plain English. At Goo, those skills help to offer our clients a strong, honest and dependable App development service.
+ </p>
+ <p>
+ <a href="http://uk.linkedin.com/in/simonw"><img class="icon" src="/images/linkedin.png" width="16" height="16" alt="Linkedin" border="0"></a> <a href="http://uk.linkedin.com/in/simonw">Simon on LinkedIn</a>
+ </p>
+ </div>
+ <div style="clear:left"></div>
+</div>
diff --git a/src/content/about.yaml b/src/content/about.yaml
new file mode 100644
index 0000000..421662b
--- /dev/null
+++ b/src/content/about.yaml
@@ -0,0 +1,2 @@
+title: "About Us"
+description: "Some background on Goo Software Ltd, the UK-based iOS development company."
diff --git a/src/content/blog.rhtml b/src/content/blog.rhtml
new file mode 100644
index 0000000..504128b
--- /dev/null
+++ b/src/content/blog.rhtml
@@ -0,0 +1,13 @@
+---
+title: Blog Index
+---
+
+<div id="content">
+ <h1>Latest blog articles</h1>
+
+ <ul class="blog-items">
+ <% for article in sorted_articles %>
+ <li><span class="date"><%= article[:created_at]%></span> <a href="<%= article.path %>"><%= article[:title] %></a></li>
+ <% end %>
+ </ul>
+</div>
diff --git a/src/content/blog/0001-app-store-review-process.md b/src/content/blog/0001-app-store-review-process.md
new file mode 100644
index 0000000..125ab6c
--- /dev/null
+++ b/src/content/blog/0001-app-store-review-process.md
@@ -0,0 +1,94 @@
+---
+kind: article
+created_at: 2010-07-24
+title: Thoughts on the App Store review process
+---
+
+I've just completed the Apple Developer Program survey, and found that the process
+really helped to focus my thoughts on the whole iOS development process, especially
+the app submission and approval process.
+
+When I talk to clients and other iOS developers about iOS development, the App Store approval
+process is raised time and again as a particular pain point. The two things that most bother
+people trying to build a business around this platform are:
+
+1. The apparent arbitrariness around whether an app is approved or rejected
+2. The lack of an SLA around approval times
+
+Regarding the former, I don't see this. The development agreement that iOS developers sign is
+pretty explicit about what is and isn't allowed on the App Store. Most questions I've had around
+whether feature X is permissible have been answered by reading the agreement. There have been some
+[well-publicised examples](ex1) of rejections that appear to be arbitrary but they're few and
+far between, and if often transpires that there's [more to the decision than is apparent at
+first glance](ex2).
+
+[ex1]: http://daringfireball.net/2009/08/ninjawords
+[ex2]: http://daringfireball.net/2009/08/phil_schiller_app_store
+
+Regarding the lack of SLA, it's definitely a real issue. The best Apple do is give an [indication](ap1)
+of "Percentage of submissions reviewed within the last 7 days", broken down into New Apps and App
+Updates. It's not even completely clear what this metric means, but it's the only thing we have.
+
+[ap1]: https://developer.apple.com/iphone/appstore/approval.html
+
+This means that, for developers hoping to target a particular app launch date, there's considerable
+uncertainty around when the app needs to be submitted. One app we're working on currently is aimed
+to coincide with a national event later this year and we can't afford to miss that window. But we
+have no idea of when the app needs to be submitted in order to hit the window, so the best we can
+do is guess and err generously on the side of caution - which in turn curtails the time we can
+spend developing the app.
+
+## Can Apple do better?
+
+In order to answer that we first have to understand why the process is currently so unpredictable.
+Apple have no control over the rate at which apps are submitted to the App Store, and I suppose
+they'd argue that they do the best they can given that uncertainty. They will undoubtedly see
+periods of peak demand where even a significantly larger review team would fall behind.
+They can't guarantee an SLA given such unpredictability.
+
+Fair enough, you might think. But is it? There are a couple of factors that suggest Apple could
+do better.
+
+### Apple knows how many developers it has
+
+All iOS developers are registered with Apple. Apple knows the size of the developer community at
+and point in time, which should at least give a rough and ready metric on predicted App Store inflow.
+
+### Apple itself often triggers the periods of peak demand
+
+Those percentages I mentioned earlier tend to dip (indicating higher latency in the approval process)
+when Apple release a new device (the iPad for example, or the iPhone 4) and developers rush to
+submit apps targetting the new device. The same is true of major iOS upgrades. You may have noticed
+a significant increase in the number of app updates in the App Store in the weeks after the iPhone 4
+and iOS4 were released as developers updated their apps with high resolution artwork and recompiled
+under SDK 4 to take advantage of fast app switching.
+
+**Apple controls these hardware and software releases**; it knows they're coming and can plan for
+them. And part of that plan should be increased capacity of the App Store review team.
+
+So here's what I'd like to see: Apple giving developers a guaranteed SLA for app submissions.
+For example, Apple guarantee all apps will be reviewed within 7 days. This means Apple has to provide
+the necessary capacity at their end to cope with peak demand and still meet SLA. That's a reasonable
+burden on Apple I think; they are after all enjoying unprecedented (and well-deserved) success with
+the App Store - but iOS developers are the geese laying the golden eggs and Apple needs to step up
+and offer them a solid foundation on which they can build their businesses as successfully as Apple has
+built its own.
+
+Consider the difference this would make to developers and their clients.
+
+**Today's situation**
+
+Client: "We need the app live by 28 September. When do we need to submit to the App Store?"
+
+Developer: "Well, no-one really knows. It we submit on 21 September then we've currently got
+an 85% chance of going live on 28 September. Submitting earlier than that increases our
+chances, but we don't know how much earlier we need to submit in order to guarantee going
+live on 28 September. So let's submit on 7 September - surely it can't take any longer than
+3 weeks?"
+
+**The situation with an SLA**
+
+Client: "We need the app live by 28 September. When do we need to submit to the App Store?"
+
+Developer: "21 September"
+
diff --git a/src/content/blog/0002-subversion-rev.md b/src/content/blog/0002-subversion-rev.md
new file mode 100644
index 0000000..c3e6cd9
--- /dev/null
+++ b/src/content/blog/0002-subversion-rev.md
@@ -0,0 +1,30 @@
+---
+kind: article
+created_at: 2010-08-03
+title: Append Subversion revision to an iPhone appâs bundle version at build time
+---
+
+Here's a dirty hack to append the current Subversion revision to the version number of an iPhone app
+automatically at build time. If your Info.plist specifies the version as 1.0 and your local Subversion
+repository is at revision 36, the version number in your compiled app will be 1.0.36.
+
+To use:
+
+1. In Xcode control-click your target and choose Add > New Build Phase > New Run Script Build Phase
+
+2. Leave shell set to /bin/sh. Copy the code below (or grab from [gist](http://gist.github.com/506429)) and paste it into the Script panel
+
+3. Close the dialog
+
+4. Drag the new build phase action so that it appears first in the list of build actions
+
+5. Build your app
+
+<script src="http://gist.github.com/506429.js?file=gistfile1.sh"></script>
+
+This is a bit of a dirty one, but it works for me. If you have suggested improvements I'm all ears so please
+leave a comment.
+
+For more on the output of svnversion, run:
+
+ $ svnversion --help
diff --git a/src/content/blog/0003-spot-the-bug.md b/src/content/blog/0003-spot-the-bug.md
new file mode 100644
index 0000000..30d8ac2
--- /dev/null
+++ b/src/content/blog/0003-spot-the-bug.md
@@ -0,0 +1,9 @@
+---
+kind: article
+created_at: 2010-08-24
+title: Spot the bug
+---
+
+This code is supposed to show an instructions view when you rotate from landscape to portrait, but sometimes it doesn't quite perform as expected. Can you see why?
+
+<script src="http://gist.github.com/546623.js?file=gistfile1.m"></script>
\ No newline at end of file
diff --git a/src/content/blog/0004-device-limit.md b/src/content/blog/0004-device-limit.md
new file mode 100644
index 0000000..b2c8453
--- /dev/null
+++ b/src/content/blog/0004-device-limit.md
@@ -0,0 +1,11 @@
+---
+kind: article
+created_at: 2010-09-06
+title: "iPhone Developer Program: Resetting your 100 device-per-year limit"
+---
+
+From [https://developer.apple.com/support/ios/program-renewals.html](https://developer.apple.com/support/ios/program-renewals.html)
+ - one to watch out for when you renew your iPhone Developer Program membership:
+
+<blockquote>When Team Agents or Admins first log into the iOS Provisioning Portal at the start of a new membership year, they will be presented with the option to remove devices and restore the device count for those removed devices. <strong>Important Note: Devices can be removed and their device count restored only up until the first new device is added.</strong> Therefore, it is important to remove all devices you are no longer using for development prior to adding any new devices.</blockquote>
+
diff --git a/src/content/blog/0005-nanoc.md b/src/content/blog/0005-nanoc.md
new file mode 100644
index 0000000..b5d4b2d
--- /dev/null
+++ b/src/content/blog/0005-nanoc.md
@@ -0,0 +1,74 @@
+---
+title: Site construction and blogging with nanoc
+kind: article
+created_at: 2010-10-20
+---
+
+Since its inception, the Goo Software website has been written as static HTML and the
+blog's been running on a Wordpress installation. It's worked fine but I've never been
+happy with the setup. On the blog side, Wordpress is OK but heavyweight for our modest
+needs, and on the main site maintaining everything as static HTML is a pain. Even with
+only a few pages there's a load of boilerplate code that needs to be kept in sync
+across pages, and on the front page there's a load of duplicate code around the
+portfolio.
+
+I'd toyed with the idea of using [Django][django] to run the site, which would allow me
+to use Django's templates system to share boilerplate code across pages, and Django's
+ORM to model stuff like apps for the portfolio, but that's getting seriously heavyweight
+for a site that seldom changes. I needed something in between static and Django. And then
+I found [nanoc][nanoc].
+
+## What is nanoc?
+
+nanoc is "a Ruby site compiler that generates static HTML". In essence, you provide content
+as *layouts* (templates) and *items* (pages), and nanoc uses those building blocks to
+generate your site. The back end strikes just the right balance between flexibility and
+simplicity, and it's nicely extensible so you're only a few lines of Ruby away from any
+missing functionality that you can't do without.
+
+## Basic workflow
+
+Using nanoc is really easy. Page content can be specified in a number of different formats,
+(I tend to use HTML for the regular website and Markdown for blog posts). You edit your page
+content then at the command line, type:
+
+ $ nanoc compile
+
+That compiles your nanoc source into your final, static web content. You can preview the
+build locally and when you're ready, deploy it as you would any static web content, e.g.
+using FTP. nanoc has built-in support for rsync so if your server supports it you can deploy
+your site without even having to fire up your favourite FTP client. Just add the deploy details
+to your site's config (which is written in YAML), for example:
+
+ deploy:
+ default:
+ dst: "goosoft@goosoftware.co.uk:~/goosoftware.co.uk"
+
+Then deploy with Rake:
+
+ $ rake deploy:rsync
+
+## Case study: the Goo Software portfolio
+
+Have a look on the [Goo front page][goo] and you'll see our funky portfolio showing some of the
+cool apps we've worked on recently. Have a look at the page source and you'll see it's basically
+a load of divs with the same internal structure, one for each app. And that static HTML is exactly
+how we used to code it - copying and pasting the div each time we added a new app.
+
+Here's how we achieve the same thing using nanoc. In the config for the index page, we've got this:
+
+<script src="http://gist.github.com/636322.js?file=index.yaml"></script>
+
+Then in the HTML, we've got this:
+
+<script src="http://gist.github.com/636326.js?file=index.rhtml"></script>
+
+If you're interested in using nanoc yourself and you're the sort of person who learns best
+by example, you can find the complete source for this site (including the blog)
+[on GitHub][goo-on-github].
+
+
+[django]: http://www.djangoproject.com/
+[nanoc]: http://nanoc.stoneship.org/
+[goo-on-github]: http://github.com/simonwhitaker/goo-website
+[goo]: http://www.goosoftware.co.uk/
\ No newline at end of file
diff --git a/src/content/blog/0006-build-and-they-might-come.md b/src/content/blog/0006-build-and-they-might-come.md
new file mode 100644
index 0000000..6ac2828
--- /dev/null
+++ b/src/content/blog/0006-build-and-they-might-come.md
@@ -0,0 +1,12 @@
+---
+title: Build and they might come
+kind: article
+created_at: 2010-11-05
+---
+
+<blockquote>Weâre making iPhone software primarily for three reasons</blockquote>
+
+[Great article][1] from Marco Arment about why just building a new hardware
+platform won't in and of itself cause developers to flock to it.
+
+[1]: http://www.marco.org/1483805627
\ No newline at end of file
diff --git a/src/content/blog/0007-debugging-in-analogue.md b/src/content/blog/0007-debugging-in-analogue.md
new file mode 100644
index 0000000..5045473
--- /dev/null
+++ b/src/content/blog/0007-debugging-in-analogue.md
@@ -0,0 +1,69 @@
+---
+kind: article
+created_at: 2010-11-08
+title: Debugging in analogue
+---
+
+One of the most interesting challenges of our recently-launched [app for The xx][appstore1] was getting the video
+synchronisation as tight as possible across multiple devices. The app uses a bit of clever logic to determine, to
+the best of its ability, the clock offsets between the various devices. The device that's playing server then uses
+that to send a trigger signal to all the devices (including itself), saying "start playing at exactly time *t*" -
+where t is adjusted for each device based on its clock offset so that all devices get the same relative trigger
+time.
+
+For example, imagine two devices, D1 and D2. D2's clock is 2 seconds ahead of D1's clock - so when D1 thinks it's
+12:00:00, D2 thinks it's 12:00:02. Once the devices are aware of this discrepancy they can compensate for it: D1
+might tell itself "start playing at 13:30:00" while telling D2 "start playing at 13:30:02". The effect is that both
+devices start playing at the same time.
+
+At least, that's the theory. In practice, iOS is a non-deterministic, multitasking operating system, and it's quite
+possible that at the alloted time it'll be busy refreshing the UI, checking for mail, or doing any number of other
+things. By the time the thread that's going to hit play on the video gets serviced the devices might have slipped
+significantly out of sync.
+
+There's no way around this, and occasionally the syncing isn't perfect (especially on older iPhone and iPod models),
+but you can mitigate the effect by having each device spin up a new, high-priority thread when they receive the
+play signal, and have this high-priority thread start the video at the alloted time.
+
+In iOS there are a number of ways of starting new threads, including [NSThread][api-nsthread],
+[NSOperationQueue][api-nsop] and [Grand Central Dispatch][api-gcd]. I was curious to know which of these methods
+yielded the most favourable results for our app. So, I set up a test scenario with a difference.
+
+First, using [Amadeus Pro][amadeus-pro] I created a WAV file containing a single, 100Hz square wave. Then I
+inserted this sound at the start of the soundtrack of a sample video. I loaded a test app that played the sample
+video onto a pair of iPod Touch 3Gs and using some audio splitters and cables, connected the iPods to the line-in
+on my MacBook Pro such that one iPod contributed the left channel and the other the right. It looked something
+like this:
+
+<img class="framed" title="Sync test hardware setup" src="/images/blog/sync-test-hardware-setup.jpg" alt="" />
+
+Then, once again in Amadeus Pro, I hit record, then hit play in my test app. Once the square wave had played I could
+stop recording, zoom in on the audio track I'd just recorded, and look at the distance between the falling edge of the
+square wave on the two channels to see the time lag between the two videos:
+
+<img class="framed" title="Sync test screenshot" src="/images/blog/sync-test-screenshot.png" alt="" />
+
+I repeated the experiment a number of times with each threading approach and compared the figures to make sure I was
+choosing the best option. Average time delay per method was as follows:
+
+<table>
+ <thead>
+ <tr><th>Method</th><th>Average time delay (ms)</th></tr>
+ </thead>
+ <tbody>
+ <tr><td>Schedule play on the main thread</td><td>114</td></tr>
+ <tr><td>NSOperationQueue</td><td>7</td></tr>
+ <tr><td>Grand Central Dispatch</td><td>9</td></tr>
+ <tr><td>NSThread</td><td>10</td></tr>
+ </tbody>
+</table>
+
+So, perhaps as expected, there's not much to choose between the three threading architectures I tried, although
+they all give performance that's an order of magnitude better than the performance you get if you schedule the
+play signal on the main thread.
+
+[appstore1]: http://itunes.apple.com/gb/app/the-xx/id394653020?mt=8
+[api-nsthread]: http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSThread_Class/Reference/Reference.html
+[api-nsop]: http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/NSOperationQueue_class/Reference/Reference.html
+[api-gcd]: http://developer.apple.com/iphone/library/documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
+[amadeus-pro]: http://www.hairersoft.com/AmadeusPro/AmadeusPro.html
\ No newline at end of file
diff --git a/src/content/blog/0008-NSURLConnection.md b/src/content/blog/0008-NSURLConnection.md
new file mode 100644
index 0000000..af1d194
--- /dev/null
+++ b/src/content/blog/0008-NSURLConnection.md
@@ -0,0 +1,97 @@
+---
+kind: article
+created_at: 2010-11-21
+title: Adding state to NSURLConnection
+---
+
+Here's a quick and simple way of adding state to NSURLConnection objects.
+
+If you've ever written Cocoa code to talk to a remote HTTP server, you've
+probably used `NSURLConnection`. The basic use case looks something like this.
+First you instantiate an NSURLConnection using an NSURLRequest object:
+
+ NSURLConnection* conn = [[NSURLConnection alloc] initWithRequest:someRequest delegate:self];
+ [conn release];
+
+Then elsewhere you write delegate methods to handle callbacks from the connection such as
+`connection:didReceiveData:` when the delegate receives data from the connection,
+`connectionDidFinishLoading:` when the connection has finished loading, or
+`connection:didFailWithError:` if it fails.
+
+The tricky thing there is: if I instantiate more than one NSURLConnection object, how do I know
+which connection the delegate methods are being called for? (If you're telling yourself it's OK,
+my code doesn't instantiate more than one NSURLConnection object at a time, ask yourself: can I
+**guarantee** that my code will **never** have more than one NSURLConnection live at any one time? If you
+can't, read on...)
+
+Here's what I'd like to be able to do in `connection:didReceiveData:`, for example:
+
+ -(void) connection:(NSURLConnection*)connection didReceiveData:(NSData*)data {
+ // buffers is an NSDictionary of previously instantiated NSMutableData
+ // objects, one per connection
+ NSMutableData *buffer = [buffers objectForKey:[connection uniqueId]];
+ [buffer appendData:data];
+ }
+
+But sadly, the `uniqueId` method on NSURLConnection doesn't exist, and there isn't any other
+similar functionality available in NSURLConnection.
+
+So I decided to solve the problem by adding an instance variable to NSURLConnection. You
+can add methods to existing classes using categories, but to add an instance variable you
+need to subclass. Here's all you need to do:
+
+ @interface GSURLConnection : NSURLConnection {
+ NSDictionary *userInfo;
+ }
+
+ @property (nonatomic, retain) NSDictionary *userInfo;
+
+ @end
+
+ @implementation GSURLConnection
+
+ @synthesize userInfo;
+
+ @end
+
+This gives you an instance variable `userInfo` that you can use to store all sorts of
+additional state in a key/value stylee. Then when you create a connection, use this:
+
+ GSURLConnection *conn = [[GSURLConnection alloc] initWithRequest:req
+ delegate:self
+ startImmediately:NO];
+
+ NSString *uniqueId = myUniqueIdGenerator();
+ NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
+ uniqueId,
+ @"uniqueId",
+ nil];
+
+ // Create an empty data buffer for this connection
+ [buffers setObject:[NSMutableData dataWithCapacity:256]
+ forKey:uniqueId];
+
+ conn.userInfo = userInfo;
+ [conn scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
+ [conn start];
+ [conn release];
+
+Then in your delegate methods, you do stuff like this:
+
+ - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
+ NSString *key = [((GSURLConnection*)connection).userInfo objectForKey:@"uniqueId"];
+ [[buffers objectForKey:key] appendData:data];
+ }
+
+
+ - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
+ NSString *key = [((GSURLConnection*)connection).userInfo objectForKey:@"uniqueId"];
+ NSData *rawData = [buffers objectForKey:key];
+ [buffers removeObjectForKey:key];
+
+ // do stuff with rawData
+ }
+
+Simple!
+
+I'm sure there are loads of ways to improve this - if you know one, add a comment!
diff --git a/src/content/blog/feed.rhtml b/src/content/blog/feed.rhtml
new file mode 100644
index 0000000..03f0a13
--- /dev/null
+++ b/src/content/blog/feed.rhtml
@@ -0,0 +1 @@
+<%= atom_feed :limit => 10 %>
\ No newline at end of file
diff --git a/src/content/contact.rhtml b/src/content/contact.rhtml
new file mode 100644
index 0000000..92c9afc
--- /dev/null
+++ b/src/content/contact.rhtml
@@ -0,0 +1,50 @@
+<div id="content">
+ <h1>
+ Contact Goo
+ </h1>
+ <p>
+ Need an iPhone, iPad or Android app? Think you might need one, but not sure? Want to know what all the fuss is about? Get in touch and we'll be happy to chat!
+ </p>
+ <div id="map">
+ <a href="http://maps.google.co.uk/maps?f=q&source=s_q&hl=en&geocode=&q=OX15+4FF&sll=51.752276,-1.255824&sspn=0.153665,0.277405&ie=UTF8&hq=&hnear=Banbury,+Oxfordshire+OX15+4FF,+United+Kingdom&z=15"><img src="/images/gmap.png" width="320" height="240" alt="Map"></a>
+ </div>
+ <table border="0" id="contact-details">
+ <tbody>
+ <tr>
+ <td>
+ <a href="http://maps.google.co.uk/maps?f=q&source=s_q&hl=en&geocode=&q=OX15+4FF&sll=51.752276,-1.255824&sspn=0.153665,0.277405&ie=UTF8&hq=&hnear=Banbury,+Oxfordshire+OX15+4FF,+United+Kingdom&z=15"><img src="/images/pin.png" width="16" height="16" alt="Location" class="icon" border="0"></a>
+ </td>
+ <td>
+ Goo Software Ltd<br>
+ Bloxham Mill<br>
+ Barford Road<br>
+ Bloxham<br>
+ OX15 4FF
+ </td>
+ </tr>
+ <tr>
+ <td></td>
+ <td>
+ +44 1295 724117
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <a href="mailto:info@goosoftware.co.uk"><img src="/images/email.png" width="16" height="16" alt="Email" class="icon" border="0"></a>
+ </td>
+ <td>
+ <a href="mailto:info@goosoftware.co.uk">info@goosoftware.co.uk</a>
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <a href="http://twitter.com/goosoftware"><img src="/images/twitter.png" width="16" height="16" alt="Twitter" class="icon" border="0"></a>
+ </td>
+ <td>
+ <a href="http://twitter.com/goosoftware">@goosoftware</a>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ <div id="end-map"></div>
+</div>
\ No newline at end of file
diff --git a/src/content/contact.yaml b/src/content/contact.yaml
new file mode 100644
index 0000000..33d5060
--- /dev/null
+++ b/src/content/contact.yaml
@@ -0,0 +1,2 @@
+title: "Contact Us"
+description: "Get contact details for Goo Software Ltd, the UK-based iOS development company."
diff --git a/src/content/css/base.css b/src/content/css/base.css
new file mode 100644
index 0000000..6c2aef1
--- /dev/null
+++ b/src/content/css/base.css
@@ -0,0 +1,131 @@
+p, div, span, td, th, li {
+ line-height: 1.3em;
+}
+
+body {
+ font-family: Helvetica, Arial, sans-serif;
+ margin: 0 auto;
+ background-color: #aaa;
+}
+
+p {
+ line-height: 1.4em;
+}
+
+h1 {
+ font-size: 22px;
+ font-weight: normal;
+}
+
+h2 {
+ font-size: 17px;
+}
+
+h3 {
+ font-size: 13px;
+}
+
+h1, h2, h3 {
+ font-family: "Century Gothic", "Helvetica Neue", Helvetica, Arial, sans-serif;
+}
+
+h1 {
+}
+
+a[href] {
+ color: #667200;
+}
+
+a:visited {
+ color: #3C4200;
+}
+
+#main {
+ padding: 0;
+ margin: 20px 0 30px 0;
+ background-color: white;
+ position: relative;
+ -moz-box-shadow: 0 4px 8px #333;
+ -webkit-box-shadow: 0 4px 8px #333;
+ box-shadow: 0 4px 8px #333;
+}
+
+/* Common bits and bobs
+----------------------------------------*/
+
+p img.icon[height="16"] {
+ vertical-align: -2px;
+ margin-right: 3px;
+}
+
+/* Header
+----------------------------------------*/
+
+#header {
+ position: relative;
+ height: 180px;
+}
+
+#logo {
+ position: absolute;
+ left: 40px;
+ top: 40px;
+}
+
+#slogan {
+ position: absolute;
+ font-size: 17px;
+ left: 130px;
+ top: 140px;
+ font-family: "Century Gothic", "Helevica Neue", Arial, Helvetica, sans-serif;
+ color: #09f;
+}
+
+/* Tabs
+----------------------------------------*/
+
+ul.tabs li {
+ list-style-type: none;
+}
+
+/* Content
+----------------------------------------*/
+
+#content {
+ color: #333;
+ padding: 0 30px 20px 30px;
+}
+
+img.framed {
+ border: 1px solid #ccc;
+ padding: 3px;
+ margin: 8px;
+}
+
+
+/* Footer
+----------------------------------------*/
+
+#footer {
+ padding: 20px 30px;
+ clear: left;
+ color: #888;
+ background-color: #f0f0f0;
+ border-top: 1px solid #ddd;
+ font-size: 11px;
+ text-shadow: #fff 0 1px 1px;
+}
+
+/* Code
+----------------------------------------*/
+
+pre, code {
+ font-family: 'Bitstream Vera Sans Mono', Courier, monospace;
+ font-size: 12px;
+}
+
+pre {
+ padding: 3px;
+ background-color: #e0e8f0;
+ border: 1px solid #ccc;
+}
diff --git a/src/content/css/blog.css b/src/content/css/blog.css
new file mode 100644
index 0000000..5c456e7
--- /dev/null
+++ b/src/content/css/blog.css
@@ -0,0 +1,146 @@
+@import url('base.css');
+
+body {
+ max-width: 1200px;
+}
+
+#header {
+ border-bottom: 1px solid #ddd;
+}
+
+#content {
+ margin-right: 220px;
+}
+
+/* Monochrome nav */
+
+#nav {
+ top: 20px;
+}
+
+#nav .tabs li a {
+ background-color: #aaa;
+ color: white;
+}
+
+#nav .tabs li a:hover {
+ background-color: #555;
+ color: white;
+}
+
+#nav .tabs li a.selected {
+ background-color: #08d;
+}
+
+/* Blog article navigation */
+.blog-nav {
+ margin: 12px 0;
+ font-size: 13px;
+}
+
+.blog-nav .nav {
+ padding: 0;
+ margin: 0;
+}
+
+.blog-nav .nav+.nav {
+ border-left: 1px dotted #aaa;
+ padding-left: 10px;
+ margin-left: 10px;
+}
+
+/* Misc blog formatting */
+
+h1 {
+ font-size: 33px;
+ line-height: 1.1em;
+}
+
+.meta {
+ color: #666;
+ font-style: italic;
+}
+
+blockquote {
+ border-left: 2px solid #08d;
+ padding-left: 20px;
+ margin-left: 20px;
+ color: #08d;
+}
+
+a[href] {
+ color: #08d;
+}
+
+a[href]:visited {
+ color: #333;
+}
+
+/* Comments */
+.comments {
+ margin-top: 30px;
+ padding-top: 15px;
+ border-top: 1px dashed #777;
+}
+
+/* Latest posts */
+
+#sidebar {
+ float: right;
+ width: 200px;
+ padding: 20px 10px;
+ margin: 0;
+ font-size: 13px;
+ text-align: right;
+ border-left: 1px solid #ddd;
+}
+
+#sidebar a {
+ color: #333;
+}
+
+#sidebar a:hover {
+ color: #09f;
+}
+
+#sidebar .subscribe a {
+ background-image: url("/images/feed-icon-14x14.png");
+ background-position: right 0;
+ background-repeat: no-repeat;
+ padding-right: 17px;
+}
+
+#sidebar h2 {
+ color: #999;
+ font-size: 20px;
+ text-transform: uppercase;
+ padding: 0;
+}
+
+#sidebar ul {
+ margin: 0;
+ padding: 0;
+}
+
+#sidebar li {
+ display: block;
+ padding: 0;
+}
+
+#sidebar li a {
+ display: block;
+ padding: 5px 0;
+}
+
+#sidebar li a.selected {
+ font-weight: bold;
+}
+
+/* Gist formatting */
+ .gist {
+ font-size: 13px;
+}
+
+#footer {
+ clear: both;
+}
\ No newline at end of file
diff --git a/src/content/css/goo.css b/src/content/css/goo.css
new file mode 100644
index 0000000..8b35814
--- /dev/null
+++ b/src/content/css/goo.css
@@ -0,0 +1,400 @@
+@import url('base.css');
+
+body {
+ width: 840px;
+}
+
+/* Header
+----------------------------------------*/
+
+#header {
+ position: relative;
+ height: 180px;
+}
+
+#logo {
+ position: absolute;
+ left: 40px;
+ top: 40px;
+}
+
+#slogan {
+ position: absolute;
+ font-size: 17px;
+ left: 130px;
+ top: 140px;
+ font-family: "Century Gothic", "Helevica Neue", Arial, Helvetica, sans-serif;
+ color: #09f;
+}
+
+/* Navigation tabs
+----------------------------------------*/
+
+#nav {
+ position: absolute;
+ right: 0px;
+ top: 40px;
+}
+
+#nav .tabs {
+ margin: 0;
+ text-align: right;
+}
+
+#nav .tabs li {
+ margin-bottom: 12px;
+}
+
+#nav .tabs li a {
+ text-decoration: none;
+ background-color: #A0B400;
+ color: white;
+ padding: 5px 10px;
+}
+
+#nav .tabs li a:hover {
+ text-decoration: none;
+ background-color: #3C4200;
+ color: white;
+ padding: 5px 10px;
+}
+
+#nav .tabs li a.selected {
+ background-color: #08d;
+}
+
+/* App showcase
+----------------------------------------*/
+
+#showcase {
+ margin: 0;
+ background-color: black;
+ background-image: url('../images/app-bg.png');
+ background-repeat: no-repeat;
+ color: #ddd;
+ position: relative;
+ width: 100%;
+}
+
+#apps {
+ border-left: 1px solid #666;
+ position: relative;
+ margin: 0;
+ width: 689px;
+ height: 500px;
+}
+
+#showcase .detail {
+ color: #aaa;
+ font-size: 13px;
+}
+
+#showcase a {
+ color: #fff;
+}
+
+.app-end {
+ clear: left;
+}
+
+#showcase .app {
+ padding: 30px;
+}
+
+#showcase .app h2 {
+ margin-top: 0;
+ font-size: 22px;
+ font-weight: bold;
+}
+
+#showcase .app h2 a {
+ text-decoration: none;
+ color: #eee;
+}
+
+#showcase .app h2 a:hover {
+ text-decoration: underline;
+}
+
+#showcase .app h2 .appslogan {
+ color: #09f;
+ font-weight: normal;
+ margin-left: 6px;
+}
+
+#showcase .app .screenshot {
+ float: left;
+ max-width: 200px;
+}
+
+#showcase .app .description {
+ margin-left: 220px;
+ padding: 0 15px;
+}
+
+#showcase .app .quotation {
+ font-style: italic;
+}
+
+#showcase .app .quotation .source {
+ font-style: normal;
+ font-weight: normal;
+ color: #666;
+ margin-left: 5px;
+}
+
+#showcase .app .install-links {
+ margin: 0 0 10px 0;
+}
+
+#showcase .app .appstore-badge {
+ padding: 0;
+}
+
+#showcase .app div.android-info {
+ float: right;
+ width: 220px;
+ font-size: 12px;
+}
+
+#showcase #page_control {
+ position: relative;
+ float: left;
+ height: 100%;
+ width: 150px;
+ top: 40px;
+ left: 0;
+ height: 100%;
+}
+
+#showcase #page_control a {
+ display: block;
+ font-size: 15px;
+ color: white;
+ padding: 10px 10px;
+ text-align: left;
+ text-decoration: none;
+ border-top: 1px solid #666;
+ border-bottom: 1px solid #666;
+}
+
+#showcase #page_control a.selected {
+ background-color: black;
+}
+
+#showcase #page_control a+a {
+ border-top-width: 0;
+}
+
+#showcase #page_control a:hover {
+ background-color: #09f;
+ color: white;
+}
+
+/* Contact page
+----------------------------------------*/
+
+#contact-details {
+ margin: 24px 0 12px 40px;
+}
+
+#contact-details td {
+ min-width: 30px;
+ padding: 0 0 10px 0;
+ vertical-align: top;
+}
+
+#map {
+ border: 1px solid #ccc;
+ padding: 4px;
+ float: right;
+}
+
+#end-map {
+ clear: right;
+}
+
+/* Support page
+----------------------------------------*/
+
+.support-steps img {
+ margin: 10px 0 30px 10px;
+ border: 1px solid #ccc;
+ padding: 3px;
+}
+
+.support-steps li+li {
+ margin-top: 6px;
+}
+
+div.support-item {
+ border-top: 1px solid #A0B400;
+ padding-top: 10px;
+ margin-top: 40px;
+}
+
+/* About page
+----------------------------------------*/
+
+.portrait {
+ float: left;
+ width: 162px;
+}
+
+.biog {
+ margin-left: 180px;
+}
+
+/* Blog index
+----------------------------------------*/
+
+ul.blog-items {
+ padding-left: 0;
+}
+
+.blog-items li {
+ list-style-type: none;
+ line-height: 1.7em;
+}
+
+.blog-items li .date {
+ color: #999;
+ font-size: 12px;
+}
+
+@media screen and (max-device-width: 480px) {
+ body {
+ width: 480px;
+ margin: 0;
+ padding: 0;
+ background-color: #fff;
+ background-image: none;
+ }
+
+ p, div, span, li {
+ font-size: 20px;
+ }
+
+ h1 {
+ font-size: 28px;
+ font-weight: normal;
+ }
+
+ h2 {
+ font-size: 24px;
+ }
+
+ h3 {
+ font-size: 20px;
+ }
+
+ #header {
+ height: 160px;
+ }
+
+ #main {
+ margin: 0;
+ padding: 0;
+ background-image: none;
+ -moz-box-shadow: none;
+ -webkit-box-shadow: none;
+ box-shadow: none;
+
+ }
+
+ #logo {
+ left: 10px;
+ top: 20px;
+ }
+
+ #slogan {
+ left: 120px;
+ width: 340px;
+ top: 120px;
+ }
+ #nav {
+ position: relative;
+ top: 0;
+ left: 0;
+ padding: 0;
+ margin: 10px 0;
+ }
+
+ #nav .tabs {
+ text-align: left;
+ padding: 0;
+ margin: 0 20px;
+ }
+
+ #nav .tabs li {
+ float: left;
+ font-size: 20px;
+ }
+
+ #nav .tabs li+li {
+ margin-left: 1px;
+ }
+
+ #content {
+ clear: both;
+ padding: 0 20px;
+ margin: 60px 0 0 0;
+ width: 440px;
+ }
+
+ #showcase {
+ width: 440px;
+ background-color: black;
+ border-radius: 0;
+ -moz-border-radius: 0;
+ padding: 0 20px;
+ margin: 20px 0 0 0;
+ }
+
+ #showcase #apps {
+ width: 100%;
+ border-width: 0;
+ height: auto;
+ }
+
+ #showcase .app h2 a {
+ }
+
+ #showcase .app+.app {
+ border-top: 1px solid #333;
+ }
+
+ #showcase .app {
+ margin: 0;
+ padding: 30px 0px;
+ }
+
+ #showcase .app img.screenshot {
+ width: 120px;
+ }
+
+ #showcase .app .description {
+ margin-left: 140px;
+ padding: 0px;
+ }
+
+ #footer {
+ margin: 0;
+ padding: 20px 10px;
+ text-align: center;
+ font-size: 10px;
+ }
+
+ #footer a {
+ }
+
+ .portrait {
+ float: left;
+ width: 60px;
+ }
+
+ .biog {
+ margin-left: 80px;
+ }
+
+}
\ No newline at end of file
diff --git a/src/content/error/404.markdown b/src/content/error/404.markdown
new file mode 100644
index 0000000..da646d4
--- /dev/null
+++ b/src/content/error/404.markdown
@@ -0,0 +1,5 @@
+# Error
+
+Oops! We couldn't find the page you were looking for.
+
+Please go back to the [Goo homepage](/) and try again.
\ No newline at end of file
diff --git a/src/content/help.rhtml b/src/content/help.rhtml
new file mode 100644
index 0000000..c204bd9
--- /dev/null
+++ b/src/content/help.rhtml
@@ -0,0 +1,70 @@
+<div id="content">
+ <h1>
+ Support
+ </h1>
+ <ul>
+ <li>
+ <a href="#get-udid">How to get your device's UDID</a>
+ </li>
+ <li>
+ <a href="#install-adhoc">How to install an Ad-Hoc build</a>
+ </li>
+ </ul>
+ <div class="support-item">
+ <h2>
+ <a name="get-udid" id="get-udid">How to get your device's UDID</a>
+ </h2>
+ <p>
+ Every iPhone, iPod and iPad has a unique device identifier, or UDID for short. We'll ask you to send us that identifier if we're building an app for you and we want to send you a preview (or "Ad-Hoc") build. Here's how to find it:
+ </p>
+ <ol class="support-steps">
+ <li>Connect your device to your computer and start iTunes
+ </li>
+ <li>Click on your device in the Devices area on the left of the iTunes window
+ <div class="image">
+ <img src="/images/support/get-udid-select-device-in-itunes.png">
+ </div>
+ </li>
+ <li>Select the summary tab in the main part of the iTunes window
+ <div class="image">
+ <img src="/images/support/get-udid-summary-view.png">
+ </div>
+ </li>
+ <li>Click on the words <strong>Serial number</strong> - this will toggle the display between your device's serial number and its UDID.
+ <div class="image">
+ <img src="/images/support/get-udid-summary-with-udid.png">
+ </div>
+ </li>
+ <li>With the UDID showing, press CMD+C (CTRL+C in Windows) or choose Copy from the Edit menu.
+ </li>
+ <li>In the application where you want to place the UDID (e.g. in an email window) press CMD+V (CTRL+V on Windows) to paste the UDID into place.
+ </li>
+ </ol>
+ </div>
+ <div class="support-item">
+ <h2>
+ <a name="install-adhoc" id="install-adhoc">How to install an Ad-Hoc build</a>
+ </h2>
+ <p>
+ When we're building an app for you we might want to send you a preview (or "Ad-Hoc") build. Here's how to install it:
+ </p>
+ <ol class="support-steps">
+ <li>We'll send you a Zip file. When you open the Zip file you'll find two files inside: the application itself and a mobile provision file.
+ <div class="image">
+ <img src="/images/support/adhoc-build-install-zip-contents.png">
+ </div>
+ </li>
+ <li>Drag <strong>both files</strong> into iTunes. Drag them onto the Library section in the top left corner of the iTunes window. You'll see a blue background if you're on target.
+ <div class="image">
+ <img src="/images/support/adhoc-build-drag-into-itunes.png">
+ </div>
+ </li>
+ <li>Plug your device into iTunes and synchronise it. The Ad-Hoc app will be copied across just like an app downloaded from the App Store.
+ </li>
+ </ol>
+ <p>
+ NB: Ad-Hoc apps only work on the specific devices for which they've been built. Don't try installing an Ad-Hoc build on another device, it won't work.
+ </p>
+ </div>
+ <div style="clear:left"></div>
+</div>
\ No newline at end of file
diff --git a/src/content/help.yaml b/src/content/help.yaml
new file mode 100644
index 0000000..66e45f5
--- /dev/null
+++ b/src/content/help.yaml
@@ -0,0 +1 @@
+title: Help
diff --git a/src/content/htaccess.txt b/src/content/htaccess.txt
new file mode 100644
index 0000000..07c59da
--- /dev/null
+++ b/src/content/htaccess.txt
@@ -0,0 +1 @@
+ErrorDocument 404 /error/404.html
diff --git a/src/content/images/app-bg.png b/src/content/images/app-bg.png
new file mode 100644
index 0000000..8f47d3c
Binary files /dev/null and b/src/content/images/app-bg.png differ
diff --git a/src/content/images/app-store-badge-clipped.png b/src/content/images/app-store-badge-clipped.png
new file mode 100644
index 0000000..ab7468c
Binary files /dev/null and b/src/content/images/app-store-badge-clipped.png differ
diff --git a/src/content/images/apps/bbc-bitesize.png b/src/content/images/apps/bbc-bitesize.png
new file mode 100644
index 0000000..84fdd49
Binary files /dev/null and b/src/content/images/apps/bbc-bitesize.png differ
diff --git a/src/content/images/apps/exam-countdown.png b/src/content/images/apps/exam-countdown.png
new file mode 100644
index 0000000..6df9d68
Binary files /dev/null and b/src/content/images/apps/exam-countdown.png differ
diff --git a/src/content/images/apps/habilis-logo-white.png b/src/content/images/apps/habilis-logo-white.png
new file mode 100644
index 0000000..e9ca23d
Binary files /dev/null and b/src/content/images/apps/habilis-logo-white.png differ
diff --git a/src/content/images/apps/habilis-logo.png b/src/content/images/apps/habilis-logo.png
new file mode 100644
index 0000000..df279d0
Binary files /dev/null and b/src/content/images/apps/habilis-logo.png differ
diff --git a/src/content/images/apps/ibreastcheck.png b/src/content/images/apps/ibreastcheck.png
new file mode 100644
index 0000000..a099f86
Binary files /dev/null and b/src/content/images/apps/ibreastcheck.png differ
diff --git a/src/content/images/apps/rsa-vision.png b/src/content/images/apps/rsa-vision.png
new file mode 100644
index 0000000..2926b06
Binary files /dev/null and b/src/content/images/apps/rsa-vision.png differ
diff --git a/src/content/images/apps/sports-massager.png b/src/content/images/apps/sports-massager.png
new file mode 100644
index 0000000..683079a
Binary files /dev/null and b/src/content/images/apps/sports-massager.png differ
diff --git a/src/content/images/apps/the-xx.png b/src/content/images/apps/the-xx.png
new file mode 100644
index 0000000..89ebaf7
Binary files /dev/null and b/src/content/images/apps/the-xx.png differ
diff --git a/src/content/images/bg-body.png b/src/content/images/bg-body.png
new file mode 100644
index 0000000..3ccfbba
Binary files /dev/null and b/src/content/images/bg-body.png differ
diff --git a/src/content/images/bg-footer.png b/src/content/images/bg-footer.png
new file mode 100644
index 0000000..d7a9a9f
Binary files /dev/null and b/src/content/images/bg-footer.png differ
diff --git a/src/content/images/blog/sync-test-hardware-setup.jpg b/src/content/images/blog/sync-test-hardware-setup.jpg
new file mode 100644
index 0000000..d7d7f6c
Binary files /dev/null and b/src/content/images/blog/sync-test-hardware-setup.jpg differ
diff --git a/src/content/images/blog/sync-test-screenshot.png b/src/content/images/blog/sync-test-screenshot.png
new file mode 100644
index 0000000..cc3fb02
Binary files /dev/null and b/src/content/images/blog/sync-test-screenshot.png differ
diff --git a/src/content/images/email.png b/src/content/images/email.png
new file mode 100644
index 0000000..5a16273
Binary files /dev/null and b/src/content/images/email.png differ
diff --git a/src/content/images/feed-icon-14x14.png b/src/content/images/feed-icon-14x14.png
new file mode 100755
index 0000000..b3c949d
Binary files /dev/null and b/src/content/images/feed-icon-14x14.png differ
diff --git a/src/content/images/feed-icon-28x28.png b/src/content/images/feed-icon-28x28.png
new file mode 100755
index 0000000..d64c669
Binary files /dev/null and b/src/content/images/feed-icon-28x28.png differ
diff --git a/src/content/images/follow_us-c.png b/src/content/images/follow_us-c.png
new file mode 100644
index 0000000..fc5374a
Binary files /dev/null and b/src/content/images/follow_us-c.png differ
diff --git a/src/content/images/gmap.png b/src/content/images/gmap.png
new file mode 100644
index 0000000..48b20c3
Binary files /dev/null and b/src/content/images/gmap.png differ
diff --git a/src/content/images/goo-logo-333.png b/src/content/images/goo-logo-333.png
new file mode 100644
index 0000000..77b8f79
Binary files /dev/null and b/src/content/images/goo-logo-333.png differ
diff --git a/src/content/images/goo-logo.png b/src/content/images/goo-logo.png
new file mode 100644
index 0000000..fc55987
Binary files /dev/null and b/src/content/images/goo-logo.png differ
diff --git a/src/content/images/linkedin.png b/src/content/images/linkedin.png
new file mode 100644
index 0000000..c78c703
Binary files /dev/null and b/src/content/images/linkedin.png differ
diff --git a/src/content/images/paging-arrow-left.png b/src/content/images/paging-arrow-left.png
new file mode 100644
index 0000000..2e23524
Binary files /dev/null and b/src/content/images/paging-arrow-left.png differ
diff --git a/src/content/images/paging-arrow-right.png b/src/content/images/paging-arrow-right.png
new file mode 100644
index 0000000..1b585b3
Binary files /dev/null and b/src/content/images/paging-arrow-right.png differ
diff --git a/src/content/images/pin.png b/src/content/images/pin.png
new file mode 100644
index 0000000..e4f8aa9
Binary files /dev/null and b/src/content/images/pin.png differ
diff --git a/src/content/images/separator.png b/src/content/images/separator.png
new file mode 100644
index 0000000..fb56d55
Binary files /dev/null and b/src/content/images/separator.png differ
diff --git a/src/content/images/showcase-bg.png b/src/content/images/showcase-bg.png
new file mode 100644
index 0000000..0c0a40a
Binary files /dev/null and b/src/content/images/showcase-bg.png differ
diff --git a/src/content/images/showcase-tab-bg.png b/src/content/images/showcase-tab-bg.png
new file mode 100644
index 0000000..415eb23
Binary files /dev/null and b/src/content/images/showcase-tab-bg.png differ
diff --git a/src/content/images/simon.jpg b/src/content/images/simon.jpg
new file mode 100644
index 0000000..8134965
Binary files /dev/null and b/src/content/images/simon.jpg differ
diff --git a/src/content/images/support/adhoc-build-drag-into-itunes.png b/src/content/images/support/adhoc-build-drag-into-itunes.png
new file mode 100644
index 0000000..fb5e55c
Binary files /dev/null and b/src/content/images/support/adhoc-build-drag-into-itunes.png differ
diff --git a/src/content/images/support/adhoc-build-install-zip-contents.png b/src/content/images/support/adhoc-build-install-zip-contents.png
new file mode 100644
index 0000000..c75d006
Binary files /dev/null and b/src/content/images/support/adhoc-build-install-zip-contents.png differ
diff --git a/src/content/images/support/get-udid-select-device-in-itunes.png b/src/content/images/support/get-udid-select-device-in-itunes.png
new file mode 100644
index 0000000..049124b
Binary files /dev/null and b/src/content/images/support/get-udid-select-device-in-itunes.png differ
diff --git a/src/content/images/support/get-udid-summary-view.png b/src/content/images/support/get-udid-summary-view.png
new file mode 100644
index 0000000..c9b5789
Binary files /dev/null and b/src/content/images/support/get-udid-summary-view.png differ
diff --git a/src/content/images/support/get-udid-summary-with-udid.png b/src/content/images/support/get-udid-summary-with-udid.png
new file mode 100644
index 0000000..3f33b3d
Binary files /dev/null and b/src/content/images/support/get-udid-summary-with-udid.png differ
diff --git a/src/content/images/twitter.png b/src/content/images/twitter.png
new file mode 100644
index 0000000..6d85d73
Binary files /dev/null and b/src/content/images/twitter.png differ
diff --git a/src/content/index.rhtml b/src/content/index.rhtml
new file mode 100644
index 0000000..d09c87b
--- /dev/null
+++ b/src/content/index.rhtml
@@ -0,0 +1,53 @@
+<div id="content">
+ <h1>
+ Welcome to Goo!
+ </h1>
+ <p>
+ We're a UK software house specialising in apps for iPhone, iPad and Android. Here's some of the stuff we've done.
+ </p>
+</div>
+<div id="showcase">
+ <div id="apps">
+
+ <% for app in @item[:apps]%>
+ <div class="app" id="<%= app[:name].downcase.gsub(' ','-') %>">
+ <a href="<%= app[:itunes_url] %>"><img src="<%= app[:image] %>" class="screenshot" alt="app screenshot" border="0"></a>
+ <div class="description">
+ <h2>
+ <a href="<%= app[:itunes_url] %>"><%= app[:name] %></a>
+ <span class="appslogan"<%if app[:slogan_colour]%> style="color:<%=app[:slogan_colour]%>"<%end%>><%= app[:slogan]%></span>
+ </h2>
+ <% for desc in app[:description]%>
+ <p><%= desc %></p>
+ <% end %>
+
+ <div class="install-links">
+ <% if app[:android_package] %>
+ <div class="android-info">
+ To install on Android, search the marketplace for <%= app[:name] %> or scan
+ <a href="http://chart.apis.google.com/chart?cht=qr&chs=400x400&chld=Q%7C3&chl=market://details?id=<%= app[:android_package] %>">this QR code</a>
+ </div>
+ <% end %>
+
+ <% if app[:itunes_url] %>
+ <div class="appstore-badge">
+ <a href="<%= app[:itunes_url] %>"><img src="/images/app-store-badge-clipped.png" alt="App Store Badge Clipped" border="0"></a>
+ </div>
+ <% end %>
+ </div>
+
+ <div style="clear:right"> </div>
+
+ <% if app[:client] %>
+ <div class="detail">Client: <%= app[:client] %></div>
+ <% end %>
+ <% if app[:platform] %>
+ <div class="detail">Platform: <%= app[:platform] %></div>
+ <% end %>
+ </div>
+ <div class="app-end"></div>
+ </div>
+ <% end %>
+
+ </div><!-- #apps -->
+</div><!-- #showcase -->
diff --git a/src/content/index.yaml b/src/content/index.yaml
new file mode 100644
index 0000000..328cdf2
--- /dev/null
+++ b/src/content/index.yaml
@@ -0,0 +1,86 @@
+title: "Fantastic Apps for iPhone, iPad and Android"
+description: "Goo Software Ltd is an independent UK-based software house specialising in development of apps for iPhone, iPad and Android."
+js_imports:
+ - showcase.js
+
+apps:
+ - name: BBC Bitesize Exam Alert
+ slogan: Track your exams the fun way
+ slogan_colour: "#39f"
+ itunes_url: http://itunes.apple.com/gb/app/gcse-bitesize-exam-alert/id414023535?mt=8
+ image: /images/apps/bbc-bitesize.png
+ description:
+ - > Our popular Exam Countdown app, re-branded
+ for the BBC Bitesize iPhone app series.
+ - > Track your forthcoming exams, get study tips
+ and share with your friends via Facebook
+ client: BBC Bitesize / Pearson Education Ltd
+ platform: iPhone and iPod Touch
+
+ - name: The xx
+ slogan: Innovative video experience
+ itunes_url: http://itunes.apple.com/gb/app/the-xx/id394653020?mt=8
+ image: /images/apps/the-xx.png
+ description:
+ - > Using this fun and unique app, you and up to two friends can
+ play tracks from the xx's award-winning debut album <em>XX</em>
+ across multiple iPhones or iPod Touches.
+ - > <span class="quotation">
+ "An ingenious use of technology"
+ <span class="source"> — The Guardian</span>
+ </span>
+ client: Beggars Group Ltd
+ platform: iPhone and iPod Touch
+
+ - name: RSA Vision
+ slogan: Enlightenment to go
+ slogan_colour: "#CE5B02"
+ itunes_url: http://itunes.apple.com/gb/app/rsa-vision/id397348011?mt=8
+ android_package: com.goocode.rsavision
+ image: /images/apps/rsa-vision.png
+ description:
+ - > The RSA Vision app brings to you the latest videos from the
+ RSA's free public events programme. You can browse by category,
+ search for videos and compile a playlist of your favourite
+ videos to watch later.
+ - (Check out the RSAnimate category - they're <em>really</em> great!)
+ client: <a href="http://www.torchbox.com/">Torchbox Ltd</a>
+ platform: "iPhone, iPod Touch, Android"
+
+ - name: iBreastCheck
+ slogan: Helping you to be breast aware
+ slogan_colour: "#C70064"
+ itunes_url: http://itunes.apple.com/gb/app/ibreastcheck/id391746205?mt=8
+ image: /images/apps/ibreastcheck.png
+ description:
+ - > iBreastCheck from breast cancer charity Breakthrough helps
+ you to be breast aware with a little TLC: Touch, Look, Check.
+ - > The app has video and slideshow content explaining how to
+ check your breasts, a reminder service to help you to remember
+ to check regularly, and more.
+ client: <a href="http://www.torchbox.com/">Torchbox Ltd</a>
+ platform: iPhone and iPod Touch
+
+ - name: Exam Countdown
+ slogan: Track your exams the fun way
+ slogan_colour: "#888"
+ itunes_url: http://itunes.apple.com/gb/app/exam-countdown/id372962356?mt=8
+ image: /images/apps/exam-countdown.png
+ description:
+ - > The Exam Countdown app allows students to keep track of
+ forthcoming exams and share their thoughts via Facebook.
+ client: Pearson Education Ltd
+ platform: iPhone and iPod Touch
+
+ - name: Sports Massager
+ itunes_url: http://itunes.apple.com/gb/app/sports-massager/id352993865?mt=8
+ slogan: Let your phone take the strain
+ slogan_colour: "#3956BD"
+ image: /images/apps/sports-massager.png
+ description:
+ - > Aching after a great workout? Let Dan The Man take the strain!
+ Just hit the button then enjoy a relaxing massage from Dan The
+ Man in this fun app - Goo's first foray onto the App Store.
+ platform: iPhone
+
+
diff --git a/src/content/js/google-analytics.js b/src/content/js/google-analytics.js
new file mode 100644
index 0000000..5e8f797
--- /dev/null
+++ b/src/content/js/google-analytics.js
@@ -0,0 +1,9 @@
+var _gaq = _gaq || [];
+_gaq.push(['_setAccount', 'UA-17175797-1']);
+_gaq.push(['_trackPageview']);
+
+(function() {
+var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
+ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
+var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
+})();
diff --git a/src/content/js/jquery-1.4.2.min.js b/src/content/js/jquery-1.4.2.min.js
new file mode 100644
index 0000000..7c24308
--- /dev/null
+++ b/src/content/js/jquery-1.4.2.min.js
@@ -0,0 +1,154 @@
+/*!
+ * jQuery JavaScript Library v1.4.2
+ * http://jquery.com/
+ *
+ * Copyright 2010, John Resig
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * Includes Sizzle.js
+ * http://sizzlejs.com/
+ * Copyright 2010, The Dojo Foundation
+ * Released under the MIT, BSD, and GPL Licenses.
+ *
+ * Date: Sat Feb 13 22:33:48 2010 -0500
+ */
+(function(A,w){function ma(){if(!c.isReady){try{s.documentElement.doScroll("left")}catch(a){setTimeout(ma,1);return}c.ready()}}function Qa(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function X(a,b,d,f,e,j){var i=a.length;if(typeof b==="object"){for(var o in b)X(a,o,b[o],f,e,d);return a}if(d!==w){f=!j&&f&&c.isFunction(d);for(o=0;o<i;o++)e(a[o],b,f?d.call(a[o],o,e(a[o],b)):d,j);return a}return i?
+e(a[0],b):w}function J(){return(new Date).getTime()}function Y(){return false}function Z(){return true}function na(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function oa(a){var b,d=[],f=[],e=arguments,j,i,o,k,n,r;i=c.data(this,"events");if(!(a.liveFired===this||!i||!i.live||a.button&&a.type==="click")){a.liveFired=this;var u=i.live.slice(0);for(k=0;k<u.length;k++){i=u[k];i.origType.replace(O,"")===a.type?f.push(i.selector):u.splice(k--,1)}j=c(a.target).closest(f,a.currentTarget);n=0;for(r=
+j.length;n<r;n++)for(k=0;k<u.length;k++){i=u[k];if(j[n].selector===i.selector){o=j[n].elem;f=null;if(i.preType==="mouseenter"||i.preType==="mouseleave")f=c(a.relatedTarget).closest(i.selector)[0];if(!f||f!==o)d.push({elem:o,handleObj:i})}}n=0;for(r=d.length;n<r;n++){j=d[n];a.currentTarget=j.elem;a.data=j.handleObj.data;a.handleObj=j.handleObj;if(j.handleObj.origHandler.apply(j.elem,e)===false){b=false;break}}return b}}function pa(a,b){return"live."+(a&&a!=="*"?a+".":"")+b.replace(/\./g,"`").replace(/ /g,
+"&")}function qa(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function ra(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var f=c.data(a[d++]),e=c.data(this,f);if(f=f&&f.events){delete e.handle;e.events={};for(var j in f)for(var i in f[j])c.event.add(this,j,f[j][i],f[j][i].data)}}})}function sa(a,b,d){var f,e,j;b=b&&b[0]?b[0].ownerDocument||b[0]:s;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&b===s&&!ta.test(a[0])&&(c.support.checkClone||!ua.test(a[0]))){e=
+true;if(j=c.fragments[a[0]])if(j!==1)f=j}if(!f){f=b.createDocumentFragment();c.clean(a,b,f,d)}if(e)c.fragments[a[0]]=j?f:1;return{fragment:f,cacheable:e}}function K(a,b){var d={};c.each(va.concat.apply([],va.slice(0,b)),function(){d[this]=a});return d}function wa(a){return"scrollTo"in a&&a.document?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var c=function(a,b){return new c.fn.init(a,b)},Ra=A.jQuery,Sa=A.$,s=A.document,T,Ta=/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,Ua=/^.[^:#\[\.,]*$/,Va=/\S/,
+Wa=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,Xa=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,P=navigator.userAgent,xa=false,Q=[],L,$=Object.prototype.toString,aa=Object.prototype.hasOwnProperty,ba=Array.prototype.push,R=Array.prototype.slice,ya=Array.prototype.indexOf;c.fn=c.prototype={init:function(a,b){var d,f;if(!a)return this;if(a.nodeType){this.context=this[0]=a;this.length=1;return this}if(a==="body"&&!b){this.context=s;this[0]=s.body;this.selector="body";this.length=1;return this}if(typeof a==="string")if((d=Ta.exec(a))&&
+(d[1]||!b))if(d[1]){f=b?b.ownerDocument||b:s;if(a=Xa.exec(a))if(c.isPlainObject(b)){a=[s.createElement(a[1])];c.fn.attr.call(a,b,true)}else a=[f.createElement(a[1])];else{a=sa([d[1]],[f]);a=(a.cacheable?a.fragment.cloneNode(true):a.fragment).childNodes}return c.merge(this,a)}else{if(b=s.getElementById(d[2])){if(b.id!==d[2])return T.find(a);this.length=1;this[0]=b}this.context=s;this.selector=a;return this}else if(!b&&/^\w+$/.test(a)){this.selector=a;this.context=s;a=s.getElementsByTagName(a);return c.merge(this,
+a)}else return!b||b.jquery?(b||T).find(a):c(b).find(a);else if(c.isFunction(a))return T.ready(a);if(a.selector!==w){this.selector=a.selector;this.context=a.context}return c.makeArray(a,this)},selector:"",jquery:"1.4.2",length:0,size:function(){return this.length},toArray:function(){return R.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this.slice(a)[0]:this[a]},pushStack:function(a,b,d){var f=c();c.isArray(a)?ba.apply(f,a):c.merge(f,a);f.prevObject=this;f.context=this.context;if(b===
+"find")f.selector=this.selector+(this.selector?" ":"")+d;else if(b)f.selector=this.selector+"."+b+"("+d+")";return f},each:function(a,b){return c.each(this,a,b)},ready:function(a){c.bindReady();if(c.isReady)a.call(s,c);else Q&&Q.push(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(R.apply(this,arguments),"slice",R.call(arguments).join(","))},map:function(a){return this.pushStack(c.map(this,
+function(b,d){return a.call(b,d,b)}))},end:function(){return this.prevObject||c(null)},push:ba,sort:[].sort,splice:[].splice};c.fn.init.prototype=c.fn;c.extend=c.fn.extend=function(){var a=arguments[0]||{},b=1,d=arguments.length,f=false,e,j,i,o;if(typeof a==="boolean"){f=a;a=arguments[1]||{};b=2}if(typeof a!=="object"&&!c.isFunction(a))a={};if(d===b){a=this;--b}for(;b<d;b++)if((e=arguments[b])!=null)for(j in e){i=a[j];o=e[j];if(a!==o)if(f&&o&&(c.isPlainObject(o)||c.isArray(o))){i=i&&(c.isPlainObject(i)||
+c.isArray(i))?i:c.isArray(o)?[]:{};a[j]=c.extend(f,i,o)}else if(o!==w)a[j]=o}return a};c.extend({noConflict:function(a){A.$=Sa;if(a)A.jQuery=Ra;return c},isReady:false,ready:function(){if(!c.isReady){if(!s.body)return setTimeout(c.ready,13);c.isReady=true;if(Q){for(var a,b=0;a=Q[b++];)a.call(s,c);Q=null}c.fn.triggerHandler&&c(s).triggerHandler("ready")}},bindReady:function(){if(!xa){xa=true;if(s.readyState==="complete")return c.ready();if(s.addEventListener){s.addEventListener("DOMContentLoaded",
+L,false);A.addEventListener("load",c.ready,false)}else if(s.attachEvent){s.attachEvent("onreadystatechange",L);A.attachEvent("onload",c.ready);var a=false;try{a=A.frameElement==null}catch(b){}s.documentElement.doScroll&&a&&ma()}}},isFunction:function(a){return $.call(a)==="[object Function]"},isArray:function(a){return $.call(a)==="[object Array]"},isPlainObject:function(a){if(!a||$.call(a)!=="[object Object]"||a.nodeType||a.setInterval)return false;if(a.constructor&&!aa.call(a,"constructor")&&!aa.call(a.constructor.prototype,
+"isPrototypeOf"))return false;var b;for(b in a);return b===w||aa.call(a,b)},isEmptyObject:function(a){for(var b in a)return false;return true},error:function(a){throw a;},parseJSON:function(a){if(typeof a!=="string"||!a)return null;a=c.trim(a);if(/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return A.JSON&&A.JSON.parse?A.JSON.parse(a):(new Function("return "+
+a))();else c.error("Invalid JSON: "+a)},noop:function(){},globalEval:function(a){if(a&&Va.test(a)){var b=s.getElementsByTagName("head")[0]||s.documentElement,d=s.createElement("script");d.type="text/javascript";if(c.support.scriptEval)d.appendChild(s.createTextNode(a));else d.text=a;b.insertBefore(d,b.firstChild);b.removeChild(d)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,b,d){var f,e=0,j=a.length,i=j===w||c.isFunction(a);if(d)if(i)for(f in a){if(b.apply(a[f],
+d)===false)break}else for(;e<j;){if(b.apply(a[e++],d)===false)break}else if(i)for(f in a){if(b.call(a[f],f,a[f])===false)break}else for(d=a[0];e<j&&b.call(d,e,d)!==false;d=a[++e]);return a},trim:function(a){return(a||"").replace(Wa,"")},makeArray:function(a,b){b=b||[];if(a!=null)a.length==null||typeof a==="string"||c.isFunction(a)||typeof a!=="function"&&a.setInterval?ba.call(b,a):c.merge(b,a);return b},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var d=0,f=b.length;d<f;d++)if(b[d]===
+a)return d;return-1},merge:function(a,b){var d=a.length,f=0;if(typeof b.length==="number")for(var e=b.length;f<e;f++)a[d++]=b[f];else for(;b[f]!==w;)a[d++]=b[f++];a.length=d;return a},grep:function(a,b,d){for(var f=[],e=0,j=a.length;e<j;e++)!d!==!b(a[e],e)&&f.push(a[e]);return f},map:function(a,b,d){for(var f=[],e,j=0,i=a.length;j<i;j++){e=b(a[j],j,d);if(e!=null)f[f.length]=e}return f.concat.apply([],f)},guid:1,proxy:function(a,b,d){if(arguments.length===2)if(typeof b==="string"){d=a;a=d[b];b=w}else if(b&&
+!c.isFunction(b)){d=b;b=w}if(!b&&a)b=function(){return a.apply(d||this,arguments)};if(a)b.guid=a.guid=a.guid||b.guid||c.guid++;return b},uaMatch:function(a){a=a.toLowerCase();a=/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version)?[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||!/compatible/.test(a)&&/(mozilla)(?:.*? rv:([\w.]+))?/.exec(a)||[];return{browser:a[1]||"",version:a[2]||"0"}},browser:{}});P=c.uaMatch(P);if(P.browser){c.browser[P.browser]=true;c.browser.version=P.version}if(c.browser.webkit)c.browser.safari=
+true;if(ya)c.inArray=function(a,b){return ya.call(b,a)};T=c(s);if(s.addEventListener)L=function(){s.removeEventListener("DOMContentLoaded",L,false);c.ready()};else if(s.attachEvent)L=function(){if(s.readyState==="complete"){s.detachEvent("onreadystatechange",L);c.ready()}};(function(){c.support={};var a=s.documentElement,b=s.createElement("script"),d=s.createElement("div"),f="script"+J();d.style.display="none";d.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
+var e=d.getElementsByTagName("*"),j=d.getElementsByTagName("a")[0];if(!(!e||!e.length||!j)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(j.getAttribute("style")),hrefNormalized:j.getAttribute("href")==="/a",opacity:/^0.55$/.test(j.style.opacity),cssFloat:!!j.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:s.createElement("select").appendChild(s.createElement("option")).selected,
+parentNode:d.removeChild(d.appendChild(s.createElement("div"))).parentNode===null,deleteExpando:true,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null};b.type="text/javascript";try{b.appendChild(s.createTextNode("window."+f+"=1;"))}catch(i){}a.insertBefore(b,a.firstChild);if(A[f]){c.support.scriptEval=true;delete A[f]}try{delete b.test}catch(o){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function k(){c.support.noCloneEvent=
+false;d.detachEvent("onclick",k)});d.cloneNode(true).fireEvent("onclick")}d=s.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=s.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var k=s.createElement("div");k.style.width=k.style.paddingLeft="1px";s.body.appendChild(k);c.boxModel=c.support.boxModel=k.offsetWidth===2;s.body.removeChild(k).style.display="none"});a=function(k){var n=
+s.createElement("div");k="on"+k;var r=k in n;if(!r){n.setAttribute(k,"return;");r=typeof n[k]==="function"}return r};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=e=j=null}})();c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var G="jQuery"+J(),Ya=0,za={};c.extend({cache:{},expando:G,noData:{embed:true,object:true,
+applet:true},data:function(a,b,d){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var f=a[G],e=c.cache;if(!f&&typeof b==="string"&&d===w)return null;f||(f=++Ya);if(typeof b==="object"){a[G]=f;e[f]=c.extend(true,{},b)}else if(!e[f]){a[G]=f;e[f]={}}a=e[f];if(d!==w)a[b]=d;return typeof b==="string"?a[b]:a}},removeData:function(a,b){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var d=a[G],f=c.cache,e=f[d];if(b){if(e){delete e[b];c.isEmptyObject(e)&&c.removeData(a)}}else{if(c.support.deleteExpando)delete a[c.expando];
+else a.removeAttribute&&a.removeAttribute(c.expando);delete f[d]}}}});c.fn.extend({data:function(a,b){if(typeof a==="undefined"&&this.length)return c.data(this[0]);else if(typeof a==="object")return this.each(function(){c.data(this,a)});var d=a.split(".");d[1]=d[1]?"."+d[1]:"";if(b===w){var f=this.triggerHandler("getData"+d[1]+"!",[d[0]]);if(f===w&&this.length)f=c.data(this[0],a);return f===w&&d[1]?this.data(d[0]):f}else return this.trigger("setData"+d[1]+"!",[d[0],b]).each(function(){c.data(this,
+a,b)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var f=c.data(a,b);if(!d)return f||[];if(!f||c.isArray(d))f=c.data(a,b,c.makeArray(d));else f.push(d);return f}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),f=d.shift();if(f==="inprogress")f=d.shift();if(f){b==="fx"&&d.unshift("inprogress");f.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b===
+w)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var Aa=/[\n\t]/g,ca=/\s+/,Za=/\r/g,$a=/href|src|style/,ab=/(button|input)/i,bb=/(button|input|object|select|textarea)/i,
+cb=/^(a|area)$/i,Ba=/radio|checkbox/;c.fn.extend({attr:function(a,b){return X(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(n){var r=c(this);r.addClass(a.call(this,n,r.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1)if(e.className){for(var j=" "+e.className+" ",
+i=e.className,o=0,k=b.length;o<k;o++)if(j.indexOf(" "+b[o]+" ")<0)i+=" "+b[o];e.className=c.trim(i)}else e.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(k){var n=c(this);n.removeClass(a.call(this,k,n.attr("class")))});if(a&&typeof a==="string"||a===w)for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1&&e.className)if(a){for(var j=(" "+e.className+" ").replace(Aa," "),i=0,o=b.length;i<o;i++)j=j.replace(" "+b[i]+" ",
+" ");e.className=c.trim(j)}else e.className=""}return this},toggleClass:function(a,b){var d=typeof a,f=typeof b==="boolean";if(c.isFunction(a))return this.each(function(e){var j=c(this);j.toggleClass(a.call(this,e,j.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var e,j=0,i=c(this),o=b,k=a.split(ca);e=k[j++];){o=f?o:!i.hasClass(e);i[o?"addClass":"removeClass"](e)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this,"__className__",this.className);this.className=
+this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(Aa," ").indexOf(a)>-1)return true;return false},val:function(a){if(a===w){var b=this[0];if(b){if(c.nodeName(b,"option"))return(b.attributes.value||{}).specified?b.value:b.text;if(c.nodeName(b,"select")){var d=b.selectedIndex,f=[],e=b.options;b=b.type==="select-one";if(d<0)return null;var j=b?d:0;for(d=b?d+1:e.length;j<d;j++){var i=
+e[j];if(i.selected){a=c(i).val();if(b)return a;f.push(a)}}return f}if(Ba.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Za,"")}return w}var o=c.isFunction(a);return this.each(function(k){var n=c(this),r=a;if(this.nodeType===1){if(o)r=a.call(this,k,n.val());if(typeof r==="number")r+="";if(c.isArray(r)&&Ba.test(this.type))this.checked=c.inArray(n.val(),r)>=0;else if(c.nodeName(this,"select")){var u=c.makeArray(r);c("option",this).each(function(){this.selected=
+c.inArray(c(this).val(),u)>=0});if(!u.length)this.selectedIndex=-1}else this.value=r}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(a,b,d,f){if(!a||a.nodeType===3||a.nodeType===8)return w;if(f&&b in c.attrFn)return c(a)[b](d);f=a.nodeType!==1||!c.isXMLDoc(a);var e=d!==w;b=f&&c.props[b]||b;if(a.nodeType===1){var j=$a.test(b);if(b in a&&f&&!j){if(e){b==="type"&&ab.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed");
+a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&b.specified?b.value:bb.test(a.nodeName)||cb.test(a.nodeName)&&a.href?0:w;return a[b]}if(!c.support.style&&f&&b==="style"){if(e)a.style.cssText=""+d;return a.style.cssText}e&&a.setAttribute(b,""+d);a=!c.support.hrefNormalized&&f&&j?a.getAttribute(b,2):a.getAttribute(b);return a===null?w:a}return c.style(a,b,d)}});var O=/\.(.*)$/,db=function(a){return a.replace(/[^\w\s\.\|`]/g,
+function(b){return"\\"+b})};c.event={add:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){if(a.setInterval&&a!==A&&!a.frameElement)a=A;var e,j;if(d.handler){e=d;d=e.handler}if(!d.guid)d.guid=c.guid++;if(j=c.data(a)){var i=j.events=j.events||{},o=j.handle;if(!o)j.handle=o=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(o.elem,arguments):w};o.elem=a;b=b.split(" ");for(var k,n=0,r;k=b[n++];){j=e?c.extend({},e):{handler:d,data:f};if(k.indexOf(".")>-1){r=k.split(".");
+k=r.shift();j.namespace=r.slice(0).sort().join(".")}else{r=[];j.namespace=""}j.type=k;j.guid=d.guid;var u=i[k],z=c.event.special[k]||{};if(!u){u=i[k]=[];if(!z.setup||z.setup.call(a,f,r,o)===false)if(a.addEventListener)a.addEventListener(k,o,false);else a.attachEvent&&a.attachEvent("on"+k,o)}if(z.add){z.add.call(a,j);if(!j.handler.guid)j.handler.guid=d.guid}u.push(j);c.event.global[k]=true}a=null}}},global:{},remove:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){var e,j=0,i,o,k,n,r,u,z=c.data(a),
+C=z&&z.events;if(z&&C){if(b&&b.type){d=b.handler;b=b.type}if(!b||typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(e in C)c.event.remove(a,e+b)}else{for(b=b.split(" ");e=b[j++];){n=e;i=e.indexOf(".")<0;o=[];if(!i){o=e.split(".");e=o.shift();k=new RegExp("(^|\\.)"+c.map(o.slice(0).sort(),db).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(r=C[e])if(d){n=c.event.special[e]||{};for(B=f||0;B<r.length;B++){u=r[B];if(d.guid===u.guid){if(i||k.test(u.namespace)){f==null&&r.splice(B--,1);n.remove&&n.remove.call(a,u)}if(f!=
+null)break}}if(r.length===0||f!=null&&r.length===1){if(!n.teardown||n.teardown.call(a,o)===false)Ca(a,e,z.handle);delete C[e]}}else for(var B=0;B<r.length;B++){u=r[B];if(i||k.test(u.namespace)){c.event.remove(a,n,u.handler,B);r.splice(B--,1)}}}if(c.isEmptyObject(C)){if(b=z.handle)b.elem=null;delete z.events;delete z.handle;c.isEmptyObject(z)&&c.removeData(a)}}}}},trigger:function(a,b,d,f){var e=a.type||a;if(!f){a=typeof a==="object"?a[G]?a:c.extend(c.Event(e),a):c.Event(e);if(e.indexOf("!")>=0){a.type=
+e=e.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[e]&&c.each(c.cache,function(){this.events&&this.events[e]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType===8)return w;a.result=w;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(f=c.data(d,"handle"))&&f.apply(d,b);f=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+e]&&d["on"+e].apply(d,b)===false)a.result=false}catch(j){}if(!a.isPropagationStopped()&&
+f)c.event.trigger(a,b,f,true);else if(!a.isDefaultPrevented()){f=a.target;var i,o=c.nodeName(f,"a")&&e==="click",k=c.event.special[e]||{};if((!k._default||k._default.call(d,a)===false)&&!o&&!(f&&f.nodeName&&c.noData[f.nodeName.toLowerCase()])){try{if(f[e]){if(i=f["on"+e])f["on"+e]=null;c.event.triggered=true;f[e]()}}catch(n){}if(i)f["on"+e]=i;c.event.triggered=false}}},handle:function(a){var b,d,f,e;a=arguments[0]=c.event.fix(a||A.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive;
+if(!b){d=a.type.split(".");a.type=d.shift();f=new RegExp("(^|\\.)"+d.slice(0).sort().join("\\.(?:.*\\.)?")+"(\\.|$)")}e=c.data(this,"events");d=e[a.type];if(e&&d){d=d.slice(0);e=0;for(var j=d.length;e<j;e++){var i=d[e];if(b||f.test(i.namespace)){a.handler=i.handler;a.data=i.data;a.handleObj=i;i=i.handler.apply(this,arguments);if(i!==w){a.result=i;if(i===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}}return a.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
+fix:function(a){if(a[G])return a;var b=a;a=c.Event(b);for(var d=this.props.length,f;d;){f=this.props[--d];a[f]=b[f]}if(!a.target)a.target=a.srcElement||s;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=s.documentElement;d=s.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop||
+d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(!a.which&&(a.charCode||a.charCode===0?a.charCode:a.keyCode))a.which=a.charCode||a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==w)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a){c.event.add(this,a.origType,c.extend({},a,{handler:oa}))},remove:function(a){var b=true,d=a.origType.replace(O,"");c.each(c.data(this,
+"events").live||[],function(){if(d===this.origType.replace(O,""))return b=false});b&&c.event.remove(this,a.origType,oa)}},beforeunload:{setup:function(a,b,d){if(this.setInterval)this.onbeforeunload=d;return false},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};var Ca=s.removeEventListener?function(a,b,d){a.removeEventListener(b,d,false)}:function(a,b,d){a.detachEvent("on"+b,d)};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent=
+a;this.type=a.type}else this.type=a;this.timeStamp=J();this[G]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=Z;var a=this.originalEvent;if(a){a.preventDefault&&a.preventDefault();a.returnValue=false}},stopPropagation:function(){this.isPropagationStopped=Z;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=Z;this.stopPropagation()},isDefaultPrevented:Y,isPropagationStopped:Y,
+isImmediatePropagationStopped:Y};var Da=function(a){var b=a.relatedTarget;try{for(;b&&b!==this;)b=b.parentNode;if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}}catch(d){}},Ea=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?Ea:Da,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?Ea:Da)}}});if(!c.support.submitBubbles)c.event.special.submit=
+{setup:function(){if(this.nodeName.toLowerCase()!=="form"){c.event.add(this,"click.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="submit"||d==="image")&&c(b).closest("form").length)return na("submit",this,arguments)});c.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="text"||d==="password")&&c(b).closest("form").length&&a.keyCode===13)return na("submit",this,arguments)})}else return false},teardown:function(){c.event.remove(this,".specialSubmit")}};
+if(!c.support.changeBubbles){var da=/textarea|input|select/i,ea,Fa=function(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(f){return f.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},fa=function(a,b){var d=a.target,f,e;if(!(!da.test(d.nodeName)||d.readOnly)){f=c.data(d,"_change_data");e=Fa(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data",
+e);if(!(f===w||e===f))if(f!=null||e){a.type="change";return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:fa,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return fa.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return fa.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a,
+"_change_data",Fa(a))}},setup:function(){if(this.type==="file")return false;for(var a in ea)c.event.add(this,a+".specialChange",ea[a]);return da.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return da.test(this.nodeName)}};ea=c.event.special.change.filters}s.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(f){f=c.event.fix(f);f.type=b;return c.event.handle.call(this,f)}c.event.special[b]={setup:function(){this.addEventListener(a,
+d,true)},teardown:function(){this.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,f,e){if(typeof d==="object"){for(var j in d)this[b](j,f,d[j],e);return this}if(c.isFunction(f)){e=f;f=w}var i=b==="one"?c.proxy(e,function(k){c(this).unbind(k,i);return e.apply(this,arguments)}):e;if(d==="unload"&&b!=="one")this.one(d,f,e);else{j=0;for(var o=this.length;j<o;j++)c.event.add(this[j],d,i,f)}return this}});c.fn.extend({unbind:function(a,b){if(typeof a==="object"&&
+!a.preventDefault)for(var d in a)this.unbind(d,a[d]);else{d=0;for(var f=this.length;d<f;d++)c.event.remove(this[d],a,b)}return this},delegate:function(a,b,d,f){return this.live(b,d,f,a)},undelegate:function(a,b,d){return arguments.length===0?this.unbind("live"):this.die(b,null,d,a)},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){a=c.Event(a);a.preventDefault();a.stopPropagation();c.event.trigger(a,b,this[0]);return a.result}},
+toggle:function(a){for(var b=arguments,d=1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(f){var e=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,e+1);f.preventDefault();return b[e].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var Ga={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};c.each(["live","die"],function(a,b){c.fn[b]=function(d,f,e,j){var i,o=0,k,n,r=j||this.selector,
+u=j?this:c(this.context);if(c.isFunction(f)){e=f;f=w}for(d=(d||"").split(" ");(i=d[o++])!=null;){j=O.exec(i);k="";if(j){k=j[0];i=i.replace(O,"")}if(i==="hover")d.push("mouseenter"+k,"mouseleave"+k);else{n=i;if(i==="focus"||i==="blur"){d.push(Ga[i]+k);i+=k}else i=(Ga[i]||i)+k;b==="live"?u.each(function(){c.event.add(this,pa(i,r),{data:f,selector:r,handler:e,origType:i,origHandler:e,preType:n})}):u.unbind(pa(i,r),e)}}return this}});c.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "),
+function(a,b){c.fn[b]=function(d){return d?this.bind(b,d):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});A.attachEvent&&!A.addEventListener&&A.attachEvent("onunload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}});(function(){function a(g){for(var h="",l,m=0;g[m];m++){l=g[m];if(l.nodeType===3||l.nodeType===4)h+=l.nodeValue;else if(l.nodeType!==8)h+=a(l.childNodes)}return h}function b(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q];
+if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1&&!p){t.sizcache=l;t.sizset=q}if(t.nodeName.toLowerCase()===h){y=t;break}t=t[g]}m[q]=y}}}function d(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q];if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1){if(!p){t.sizcache=l;t.sizset=q}if(typeof h!=="string"){if(t===h){y=true;break}}else if(k.filter(h,[t]).length>0){y=t;break}}t=t[g]}m[q]=y}}}var f=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
+e=0,j=Object.prototype.toString,i=false,o=true;[0,0].sort(function(){o=false;return 0});var k=function(g,h,l,m){l=l||[];var q=h=h||s;if(h.nodeType!==1&&h.nodeType!==9)return[];if(!g||typeof g!=="string")return l;for(var p=[],v,t,y,S,H=true,M=x(h),I=g;(f.exec(""),v=f.exec(I))!==null;){I=v[3];p.push(v[1]);if(v[2]){S=v[3];break}}if(p.length>1&&r.exec(g))if(p.length===2&&n.relative[p[0]])t=ga(p[0]+p[1],h);else for(t=n.relative[p[0]]?[h]:k(p.shift(),h);p.length;){g=p.shift();if(n.relative[g])g+=p.shift();
+t=ga(g,t)}else{if(!m&&p.length>1&&h.nodeType===9&&!M&&n.match.ID.test(p[0])&&!n.match.ID.test(p[p.length-1])){v=k.find(p.shift(),h,M);h=v.expr?k.filter(v.expr,v.set)[0]:v.set[0]}if(h){v=m?{expr:p.pop(),set:z(m)}:k.find(p.pop(),p.length===1&&(p[0]==="~"||p[0]==="+")&&h.parentNode?h.parentNode:h,M);t=v.expr?k.filter(v.expr,v.set):v.set;if(p.length>0)y=z(t);else H=false;for(;p.length;){var D=p.pop();v=D;if(n.relative[D])v=p.pop();else D="";if(v==null)v=h;n.relative[D](y,v,M)}}else y=[]}y||(y=t);y||k.error(D||
+g);if(j.call(y)==="[object Array]")if(H)if(h&&h.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&E(h,y[g])))l.push(t[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&l.push(t[g]);else l.push.apply(l,y);else z(y,l);if(S){k(S,q,l,m);k.uniqueSort(l)}return l};k.uniqueSort=function(g){if(B){i=o;g.sort(B);if(i)for(var h=1;h<g.length;h++)g[h]===g[h-1]&&g.splice(h--,1)}return g};k.matches=function(g,h){return k(g,null,null,h)};k.find=function(g,h,l){var m,q;if(!g)return[];
+for(var p=0,v=n.order.length;p<v;p++){var t=n.order[p];if(q=n.leftMatch[t].exec(g)){var y=q[1];q.splice(1,1);if(y.substr(y.length-1)!=="\\"){q[1]=(q[1]||"").replace(/\\/g,"");m=n.find[t](q,h,l);if(m!=null){g=g.replace(n.match[t],"");break}}}}m||(m=h.getElementsByTagName("*"));return{set:m,expr:g}};k.filter=function(g,h,l,m){for(var q=g,p=[],v=h,t,y,S=h&&h[0]&&x(h[0]);g&&h.length;){for(var H in n.filter)if((t=n.leftMatch[H].exec(g))!=null&&t[2]){var M=n.filter[H],I,D;D=t[1];y=false;t.splice(1,1);if(D.substr(D.length-
+1)!=="\\"){if(v===p)p=[];if(n.preFilter[H])if(t=n.preFilter[H](t,v,l,p,m,S)){if(t===true)continue}else y=I=true;if(t)for(var U=0;(D=v[U])!=null;U++)if(D){I=M(D,t,U,v);var Ha=m^!!I;if(l&&I!=null)if(Ha)y=true;else v[U]=false;else if(Ha){p.push(D);y=true}}if(I!==w){l||(v=p);g=g.replace(n.match[H],"");if(!y)return[];break}}}if(g===q)if(y==null)k.error(g);else break;q=g}return v};k.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var n=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF-]|\\.)+)/,
+CLASS:/\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}},
+relative:{"+":function(g,h){var l=typeof h==="string",m=l&&!/\W/.test(h);l=l&&!m;if(m)h=h.toLowerCase();m=0;for(var q=g.length,p;m<q;m++)if(p=g[m]){for(;(p=p.previousSibling)&&p.nodeType!==1;);g[m]=l||p&&p.nodeName.toLowerCase()===h?p||false:p===h}l&&k.filter(h,g,true)},">":function(g,h){var l=typeof h==="string";if(l&&!/\W/.test(h)){h=h.toLowerCase();for(var m=0,q=g.length;m<q;m++){var p=g[m];if(p){l=p.parentNode;g[m]=l.nodeName.toLowerCase()===h?l:false}}}else{m=0;for(q=g.length;m<q;m++)if(p=g[m])g[m]=
+l?p.parentNode:p.parentNode===h;l&&k.filter(h,g,true)}},"":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("parentNode",h,m,g,p,l)},"~":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("previousSibling",h,m,g,p,l)}},find:{ID:function(g,h,l){if(typeof h.getElementById!=="undefined"&&!l)return(g=h.getElementById(g[1]))?[g]:[]},NAME:function(g,h){if(typeof h.getElementsByName!=="undefined"){var l=[];
+h=h.getElementsByName(g[1]);for(var m=0,q=h.length;m<q;m++)h[m].getAttribute("name")===g[1]&&l.push(h[m]);return l.length===0?null:l}},TAG:function(g,h){return h.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,h,l,m,q,p){g=" "+g[1].replace(/\\/g,"")+" ";if(p)return g;p=0;for(var v;(v=h[p])!=null;p++)if(v)if(q^(v.className&&(" "+v.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))l||m.push(v);else if(l)h[p]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()},
+CHILD:function(g){if(g[1]==="nth"){var h=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=h[1]+(h[2]||1)-0;g[3]=h[3]-0}g[0]=e++;return g},ATTR:function(g,h,l,m,q,p){h=g[1].replace(/\\/g,"");if(!p&&n.attrMap[h])g[1]=n.attrMap[h];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,h,l,m,q){if(g[1]==="not")if((f.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=k(g[3],null,null,h);else{g=k.filter(g[3],h,l,true^q);l||m.push.apply(m,
+g);return false}else if(n.match.POS.test(g[0])||n.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled===true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,h,l){return!!k(l[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)},
+text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"===g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}},
+setFilters:{first:function(g,h){return h===0},last:function(g,h,l,m){return h===m.length-1},even:function(g,h){return h%2===0},odd:function(g,h){return h%2===1},lt:function(g,h,l){return h<l[3]-0},gt:function(g,h,l){return h>l[3]-0},nth:function(g,h,l){return l[3]-0===h},eq:function(g,h,l){return l[3]-0===h}},filter:{PSEUDO:function(g,h,l,m){var q=h[1],p=n.filters[q];if(p)return p(g,l,h,m);else if(q==="contains")return(g.textContent||g.innerText||a([g])||"").indexOf(h[3])>=0;else if(q==="not"){h=
+h[3];l=0;for(m=h.length;l<m;l++)if(h[l]===g)return false;return true}else k.error("Syntax error, unrecognized expression: "+q)},CHILD:function(g,h){var l=h[1],m=g;switch(l){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(l==="first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":l=h[2];var q=h[3];if(l===1&&q===0)return true;h=h[0];var p=g.parentNode;if(p&&(p.sizcache!==h||!g.nodeIndex)){var v=0;for(m=p.firstChild;m;m=
+m.nextSibling)if(m.nodeType===1)m.nodeIndex=++v;p.sizcache=h}g=g.nodeIndex-q;return l===0?g===0:g%l===0&&g/l>=0}},ID:function(g,h){return g.nodeType===1&&g.getAttribute("id")===h},TAG:function(g,h){return h==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===h},CLASS:function(g,h){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(h)>-1},ATTR:function(g,h){var l=h[1];g=n.attrHandle[l]?n.attrHandle[l](g):g[l]!=null?g[l]:g.getAttribute(l);l=g+"";var m=h[2];h=h[4];return g==null?m==="!=":m===
+"="?l===h:m==="*="?l.indexOf(h)>=0:m==="~="?(" "+l+" ").indexOf(h)>=0:!h?l&&g!==false:m==="!="?l!==h:m==="^="?l.indexOf(h)===0:m==="$="?l.substr(l.length-h.length)===h:m==="|="?l===h||l.substr(0,h.length+1)===h+"-":false},POS:function(g,h,l,m){var q=n.setFilters[h[2]];if(q)return q(g,l,h,m)}}},r=n.match.POS;for(var u in n.match){n.match[u]=new RegExp(n.match[u].source+/(?![^\[]*\])(?![^\(]*\))/.source);n.leftMatch[u]=new RegExp(/(^(?:.|\r|\n)*?)/.source+n.match[u].source.replace(/\\(\d+)/g,function(g,
+h){return"\\"+(h-0+1)}))}var z=function(g,h){g=Array.prototype.slice.call(g,0);if(h){h.push.apply(h,g);return h}return g};try{Array.prototype.slice.call(s.documentElement.childNodes,0)}catch(C){z=function(g,h){h=h||[];if(j.call(g)==="[object Array]")Array.prototype.push.apply(h,g);else if(typeof g.length==="number")for(var l=0,m=g.length;l<m;l++)h.push(g[l]);else for(l=0;g[l];l++)h.push(g[l]);return h}}var B;if(s.documentElement.compareDocumentPosition)B=function(g,h){if(!g.compareDocumentPosition||
+!h.compareDocumentPosition){if(g==h)i=true;return g.compareDocumentPosition?-1:1}g=g.compareDocumentPosition(h)&4?-1:g===h?0:1;if(g===0)i=true;return g};else if("sourceIndex"in s.documentElement)B=function(g,h){if(!g.sourceIndex||!h.sourceIndex){if(g==h)i=true;return g.sourceIndex?-1:1}g=g.sourceIndex-h.sourceIndex;if(g===0)i=true;return g};else if(s.createRange)B=function(g,h){if(!g.ownerDocument||!h.ownerDocument){if(g==h)i=true;return g.ownerDocument?-1:1}var l=g.ownerDocument.createRange(),m=
+h.ownerDocument.createRange();l.setStart(g,0);l.setEnd(g,0);m.setStart(h,0);m.setEnd(h,0);g=l.compareBoundaryPoints(Range.START_TO_END,m);if(g===0)i=true;return g};(function(){var g=s.createElement("div"),h="script"+(new Date).getTime();g.innerHTML="<a name='"+h+"'/>";var l=s.documentElement;l.insertBefore(g,l.firstChild);if(s.getElementById(h)){n.find.ID=function(m,q,p){if(typeof q.getElementById!=="undefined"&&!p)return(q=q.getElementById(m[1]))?q.id===m[1]||typeof q.getAttributeNode!=="undefined"&&
+q.getAttributeNode("id").nodeValue===m[1]?[q]:w:[]};n.filter.ID=function(m,q){var p=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&p&&p.nodeValue===q}}l.removeChild(g);l=g=null})();(function(){var g=s.createElement("div");g.appendChild(s.createComment(""));if(g.getElementsByTagName("*").length>0)n.find.TAG=function(h,l){l=l.getElementsByTagName(h[1]);if(h[1]==="*"){h=[];for(var m=0;l[m];m++)l[m].nodeType===1&&h.push(l[m]);l=h}return l};g.innerHTML="<a href='#'></a>";
+if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")n.attrHandle.href=function(h){return h.getAttribute("href",2)};g=null})();s.querySelectorAll&&function(){var g=k,h=s.createElement("div");h.innerHTML="<p class='TEST'></p>";if(!(h.querySelectorAll&&h.querySelectorAll(".TEST").length===0)){k=function(m,q,p,v){q=q||s;if(!v&&q.nodeType===9&&!x(q))try{return z(q.querySelectorAll(m),p)}catch(t){}return g(m,q,p,v)};for(var l in g)k[l]=g[l];h=null}}();
+(function(){var g=s.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){n.order.splice(1,0,"CLASS");n.find.CLASS=function(h,l,m){if(typeof l.getElementsByClassName!=="undefined"&&!m)return l.getElementsByClassName(h[1])};g=null}}})();var E=s.compareDocumentPosition?function(g,h){return!!(g.compareDocumentPosition(h)&16)}:
+function(g,h){return g!==h&&(g.contains?g.contains(h):true)},x=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false},ga=function(g,h){var l=[],m="",q;for(h=h.nodeType?[h]:h;q=n.match.PSEUDO.exec(g);){m+=q[0];g=g.replace(n.match.PSEUDO,"")}g=n.relative[g]?g+"*":g;q=0;for(var p=h.length;q<p;q++)k(g,h[q],l);return k.filter(m,l)};c.find=k;c.expr=k.selectors;c.expr[":"]=c.expr.filters;c.unique=k.uniqueSort;c.text=a;c.isXMLDoc=x;c.contains=E})();var eb=/Until$/,fb=/^(?:parents|prevUntil|prevAll)/,
+gb=/,/;R=Array.prototype.slice;var Ia=function(a,b,d){if(c.isFunction(b))return c.grep(a,function(e,j){return!!b.call(e,j,e)===d});else if(b.nodeType)return c.grep(a,function(e){return e===b===d});else if(typeof b==="string"){var f=c.grep(a,function(e){return e.nodeType===1});if(Ua.test(b))return c.filter(b,f,!d);else b=c.filter(b,f)}return c.grep(a,function(e){return c.inArray(e,b)>=0===d})};c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,f=0,e=this.length;f<e;f++){d=b.length;
+c.find(a,this[f],b);if(f>0)for(var j=d;j<b.length;j++)for(var i=0;i<d;i++)if(b[i]===b[j]){b.splice(j--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,f=b.length;d<f;d++)if(c.contains(this,b[d]))return true})},not:function(a){return this.pushStack(Ia(this,a,false),"not",a)},filter:function(a){return this.pushStack(Ia(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){if(c.isArray(a)){var d=[],f=this[0],e,j=
+{},i;if(f&&a.length){e=0;for(var o=a.length;e<o;e++){i=a[e];j[i]||(j[i]=c.expr.match.POS.test(i)?c(i,b||this.context):i)}for(;f&&f.ownerDocument&&f!==b;){for(i in j){e=j[i];if(e.jquery?e.index(f)>-1:c(f).is(e)){d.push({selector:i,elem:f});delete j[i]}}f=f.parentNode}}return d}var k=c.expr.match.POS.test(a)?c(a,b||this.context):null;return this.map(function(n,r){for(;r&&r.ownerDocument&&r!==b;){if(k?k.index(r)>-1:c(r).is(a))return r;r=r.parentNode}return null})},index:function(a){if(!a||typeof a===
+"string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){a=typeof a==="string"?c(a,b||this.context):c.makeArray(a);b=c.merge(this.get(),a);return this.pushStack(qa(a[0])||qa(b[0])?b:c.unique(b))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode",
+d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")?
+a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,b){c.fn[a]=function(d,f){var e=c.map(this,b,d);eb.test(a)||(f=d);if(f&&typeof f==="string")e=c.filter(f,e);e=this.length>1?c.unique(e):e;if((this.length>1||gb.test(f))&&fb.test(a))e=e.reverse();return this.pushStack(e,a,R.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return c.find.matches(a,b)},dir:function(a,b,d){var f=[];for(a=a[b];a&&a.nodeType!==9&&(d===w||a.nodeType!==1||!c(a).is(d));){a.nodeType===
+1&&f.push(a);a=a[b]}return f},nth:function(a,b,d){b=b||1;for(var f=0;a;a=a[d])if(a.nodeType===1&&++f===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var Ja=/ jQuery\d+="(?:\d+|null)"/g,V=/^\s+/,Ka=/(<([\w:]+)[^>]*?)\/>/g,hb=/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,La=/<([\w:]+)/,ib=/<tbody/i,jb=/<|&#?\w+;/,ta=/<script|<object|<embed|<option|<style/i,ua=/checked\s*(?:[^=]|=\s*.checked.)/i,Ma=function(a,b,d){return hb.test(d)?
+a:b+"></"+d+">"},F={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};F.optgroup=F.option;F.tbody=F.tfoot=F.colgroup=F.caption=F.thead;F.th=F.td;if(!c.support.htmlSerialize)F._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d=
+c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==w)return this.empty().append((this[0]&&this[0].ownerDocument||s).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this},
+wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})},
+prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,
+this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,f;(f=this[d])!=null;d++)if(!a||c.filter(a,[f]).length){if(!b&&f.nodeType===1){c.cleanData(f.getElementsByTagName("*"));c.cleanData([f])}f.parentNode&&f.parentNode.removeChild(f)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChild;)b.removeChild(b.firstChild);
+return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,f=this.ownerDocument;if(!d){d=f.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(Ja,"").replace(/=([^="'>\s]+\/)>/g,'="$1">').replace(V,"")],f)[0]}else return this.cloneNode(true)});if(a===true){ra(this,b);ra(this.find("*"),b.find("*"))}return b},html:function(a){if(a===w)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Ja,
+""):null;else if(typeof a==="string"&&!ta.test(a)&&(c.support.leadingWhitespace||!V.test(a))&&!F[(La.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Ka,Ma);try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(f){this.empty().append(a)}}else c.isFunction(a)?this.each(function(e){var j=c(this),i=j.html();j.empty().append(function(){return a.call(this,e,i)})}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&
+this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d=c(this),f=d.html();d.replaceWith(a.call(this,b,f))});if(typeof a!=="string")a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){function f(u){return c.nodeName(u,"table")?u.getElementsByTagName("tbody")[0]||
+u.appendChild(u.ownerDocument.createElement("tbody")):u}var e,j,i=a[0],o=[],k;if(!c.support.checkClone&&arguments.length===3&&typeof i==="string"&&ua.test(i))return this.each(function(){c(this).domManip(a,b,d,true)});if(c.isFunction(i))return this.each(function(u){var z=c(this);a[0]=i.call(this,u,b?z.html():w);z.domManip(a,b,d)});if(this[0]){e=i&&i.parentNode;e=c.support.parentNode&&e&&e.nodeType===11&&e.childNodes.length===this.length?{fragment:e}:sa(a,this,o);k=e.fragment;if(j=k.childNodes.length===
+1?(k=k.firstChild):k.firstChild){b=b&&c.nodeName(j,"tr");for(var n=0,r=this.length;n<r;n++)d.call(b?f(this[n],j):this[n],n>0||e.cacheable||this.length>1?k.cloneNode(true):k)}o.length&&c.each(o,Qa)}return this}});c.fragments={};c.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var f=[];d=c(d);var e=this.length===1&&this[0].parentNode;if(e&&e.nodeType===11&&e.childNodes.length===1&&d.length===1){d[b](this[0]);
+return this}else{e=0;for(var j=d.length;e<j;e++){var i=(e>0?this.clone(true):this).get();c.fn[b].apply(c(d[e]),i);f=f.concat(i)}return this.pushStack(f,a,d.selector)}}});c.extend({clean:function(a,b,d,f){b=b||s;if(typeof b.createElement==="undefined")b=b.ownerDocument||b[0]&&b[0].ownerDocument||s;for(var e=[],j=0,i;(i=a[j])!=null;j++){if(typeof i==="number")i+="";if(i){if(typeof i==="string"&&!jb.test(i))i=b.createTextNode(i);else if(typeof i==="string"){i=i.replace(Ka,Ma);var o=(La.exec(i)||["",
+""])[1].toLowerCase(),k=F[o]||F._default,n=k[0],r=b.createElement("div");for(r.innerHTML=k[1]+i+k[2];n--;)r=r.lastChild;if(!c.support.tbody){n=ib.test(i);o=o==="table"&&!n?r.firstChild&&r.firstChild.childNodes:k[1]==="<table>"&&!n?r.childNodes:[];for(k=o.length-1;k>=0;--k)c.nodeName(o[k],"tbody")&&!o[k].childNodes.length&&o[k].parentNode.removeChild(o[k])}!c.support.leadingWhitespace&&V.test(i)&&r.insertBefore(b.createTextNode(V.exec(i)[0]),r.firstChild);i=r.childNodes}if(i.nodeType)e.push(i);else e=
+c.merge(e,i)}}if(d)for(j=0;e[j];j++)if(f&&c.nodeName(e[j],"script")&&(!e[j].type||e[j].type.toLowerCase()==="text/javascript"))f.push(e[j].parentNode?e[j].parentNode.removeChild(e[j]):e[j]);else{e[j].nodeType===1&&e.splice.apply(e,[j+1,0].concat(c.makeArray(e[j].getElementsByTagName("script"))));d.appendChild(e[j])}return e},cleanData:function(a){for(var b,d,f=c.cache,e=c.event.special,j=c.support.deleteExpando,i=0,o;(o=a[i])!=null;i++)if(d=o[c.expando]){b=f[d];if(b.events)for(var k in b.events)e[k]?
+c.event.remove(o,k):Ca(o,k,b.handle);if(j)delete o[c.expando];else o.removeAttribute&&o.removeAttribute(c.expando);delete f[d]}}});var kb=/z-?index|font-?weight|opacity|zoom|line-?height/i,Na=/alpha\([^)]*\)/,Oa=/opacity=([^)]*)/,ha=/float/i,ia=/-([a-z])/ig,lb=/([A-Z])/g,mb=/^-?\d+(?:px)?$/i,nb=/^-?\d/,ob={position:"absolute",visibility:"hidden",display:"block"},pb=["Left","Right"],qb=["Top","Bottom"],rb=s.defaultView&&s.defaultView.getComputedStyle,Pa=c.support.cssFloat?"cssFloat":"styleFloat",ja=
+function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){return X(this,a,b,true,function(d,f,e){if(e===w)return c.curCSS(d,f);if(typeof e==="number"&&!kb.test(f))e+="px";c.style(d,f,e)})};c.extend({style:function(a,b,d){if(!a||a.nodeType===3||a.nodeType===8)return w;if((b==="width"||b==="height")&&parseFloat(d)<0)d=w;var f=a.style||a,e=d!==w;if(!c.support.opacity&&b==="opacity"){if(e){f.zoom=1;b=parseInt(d,10)+""==="NaN"?"":"alpha(opacity="+d*100+")";a=f.filter||c.curCSS(a,"filter")||"";f.filter=
+Na.test(a)?a.replace(Na,b):b}return f.filter&&f.filter.indexOf("opacity=")>=0?parseFloat(Oa.exec(f.filter)[1])/100+"":""}if(ha.test(b))b=Pa;b=b.replace(ia,ja);if(e)f[b]=d;return f[b]},css:function(a,b,d,f){if(b==="width"||b==="height"){var e,j=b==="width"?pb:qb;function i(){e=b==="width"?a.offsetWidth:a.offsetHeight;f!=="border"&&c.each(j,function(){f||(e-=parseFloat(c.curCSS(a,"padding"+this,true))||0);if(f==="margin")e+=parseFloat(c.curCSS(a,"margin"+this,true))||0;else e-=parseFloat(c.curCSS(a,
+"border"+this+"Width",true))||0})}a.offsetWidth!==0?i():c.swap(a,ob,i);return Math.max(0,Math.round(e))}return c.curCSS(a,b,d)},curCSS:function(a,b,d){var f,e=a.style;if(!c.support.opacity&&b==="opacity"&&a.currentStyle){f=Oa.test(a.currentStyle.filter||"")?parseFloat(RegExp.$1)/100+"":"";return f===""?"1":f}if(ha.test(b))b=Pa;if(!d&&e&&e[b])f=e[b];else if(rb){if(ha.test(b))b="float";b=b.replace(lb,"-$1").toLowerCase();e=a.ownerDocument.defaultView;if(!e)return null;if(a=e.getComputedStyle(a,null))f=
+a.getPropertyValue(b);if(b==="opacity"&&f==="")f="1"}else if(a.currentStyle){d=b.replace(ia,ja);f=a.currentStyle[b]||a.currentStyle[d];if(!mb.test(f)&&nb.test(f)){b=e.left;var j=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;e.left=d==="fontSize"?"1em":f||0;f=e.pixelLeft+"px";e.left=b;a.runtimeStyle.left=j}}return f},swap:function(a,b,d){var f={};for(var e in b){f[e]=a.style[e];a.style[e]=b[e]}d.call(a);for(e in b)a.style[e]=f[e]}});if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b=
+a.offsetWidth,d=a.offsetHeight,f=a.nodeName.toLowerCase()==="tr";return b===0&&d===0&&!f?true:b>0&&d>0&&!f?false:c.curCSS(a,"display")==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var sb=J(),tb=/<script(.|\s)*?\/script>/gi,ub=/select|textarea/i,vb=/color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,N=/=\?(&|$)/,ka=/\?/,wb=/(\?|&)_=.*?(&|$)/,xb=/^(\w+:)?\/\/([^\/?#]+)/,yb=/%20/g,zb=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!==
+"string")return zb.call(this,a);else if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var e=a.slice(f,a.length);a=a.slice(0,f)}f="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b==="object"){b=c.param(b,c.ajaxSettings.traditional);f="POST"}var j=this;c.ajax({url:a,type:f,dataType:"html",data:b,complete:function(i,o){if(o==="success"||o==="notmodified")j.html(e?c("<div />").append(i.responseText.replace(tb,"")).find(e):i.responseText);d&&j.each(d,[i.responseText,o,i])}});return this},
+serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ub.test(this.nodeName)||vb.test(this.type))}).map(function(a,b){a=c(this).val();return a==null?null:c.isArray(a)?c.map(a,function(d){return{name:b.name,value:d}}):{name:b.name,value:a}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),
+function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:f})},getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:f})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href,
+global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:A.XMLHttpRequest&&(A.location.protocol!=="file:"||!A.ActiveXObject)?function(){return new A.XMLHttpRequest}:function(){try{return new A.ActiveXObject("Microsoft.XMLHTTP")}catch(a){}},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},etag:{},ajax:function(a){function b(){e.success&&
+e.success.call(k,o,i,x);e.global&&f("ajaxSuccess",[x,e])}function d(){e.complete&&e.complete.call(k,x,i);e.global&&f("ajaxComplete",[x,e]);e.global&&!--c.active&&c.event.trigger("ajaxStop")}function f(q,p){(e.context?c(e.context):c.event).trigger(q,p)}var e=c.extend(true,{},c.ajaxSettings,a),j,i,o,k=a&&a.context||e,n=e.type.toUpperCase();if(e.data&&e.processData&&typeof e.data!=="string")e.data=c.param(e.data,e.traditional);if(e.dataType==="jsonp"){if(n==="GET")N.test(e.url)||(e.url+=(ka.test(e.url)?
+"&":"?")+(e.jsonp||"callback")+"=?");else if(!e.data||!N.test(e.data))e.data=(e.data?e.data+"&":"")+(e.jsonp||"callback")+"=?";e.dataType="json"}if(e.dataType==="json"&&(e.data&&N.test(e.data)||N.test(e.url))){j=e.jsonpCallback||"jsonp"+sb++;if(e.data)e.data=(e.data+"").replace(N,"="+j+"$1");e.url=e.url.replace(N,"="+j+"$1");e.dataType="script";A[j]=A[j]||function(q){o=q;b();d();A[j]=w;try{delete A[j]}catch(p){}z&&z.removeChild(C)}}if(e.dataType==="script"&&e.cache===null)e.cache=false;if(e.cache===
+false&&n==="GET"){var r=J(),u=e.url.replace(wb,"$1_="+r+"$2");e.url=u+(u===e.url?(ka.test(e.url)?"&":"?")+"_="+r:"")}if(e.data&&n==="GET")e.url+=(ka.test(e.url)?"&":"?")+e.data;e.global&&!c.active++&&c.event.trigger("ajaxStart");r=(r=xb.exec(e.url))&&(r[1]&&r[1]!==location.protocol||r[2]!==location.host);if(e.dataType==="script"&&n==="GET"&&r){var z=s.getElementsByTagName("head")[0]||s.documentElement,C=s.createElement("script");C.src=e.url;if(e.scriptCharset)C.charset=e.scriptCharset;if(!j){var B=
+false;C.onload=C.onreadystatechange=function(){if(!B&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){B=true;b();d();C.onload=C.onreadystatechange=null;z&&C.parentNode&&z.removeChild(C)}}}z.insertBefore(C,z.firstChild);return w}var E=false,x=e.xhr();if(x){e.username?x.open(n,e.url,e.async,e.username,e.password):x.open(n,e.url,e.async);try{if(e.data||a&&a.contentType)x.setRequestHeader("Content-Type",e.contentType);if(e.ifModified){c.lastModified[e.url]&&x.setRequestHeader("If-Modified-Since",
+c.lastModified[e.url]);c.etag[e.url]&&x.setRequestHeader("If-None-Match",c.etag[e.url])}r||x.setRequestHeader("X-Requested-With","XMLHttpRequest");x.setRequestHeader("Accept",e.dataType&&e.accepts[e.dataType]?e.accepts[e.dataType]+", */*":e.accepts._default)}catch(ga){}if(e.beforeSend&&e.beforeSend.call(k,x,e)===false){e.global&&!--c.active&&c.event.trigger("ajaxStop");x.abort();return false}e.global&&f("ajaxSend",[x,e]);var g=x.onreadystatechange=function(q){if(!x||x.readyState===0||q==="abort"){E||
+d();E=true;if(x)x.onreadystatechange=c.noop}else if(!E&&x&&(x.readyState===4||q==="timeout")){E=true;x.onreadystatechange=c.noop;i=q==="timeout"?"timeout":!c.httpSuccess(x)?"error":e.ifModified&&c.httpNotModified(x,e.url)?"notmodified":"success";var p;if(i==="success")try{o=c.httpData(x,e.dataType,e)}catch(v){i="parsererror";p=v}if(i==="success"||i==="notmodified")j||b();else c.handleError(e,x,i,p);d();q==="timeout"&&x.abort();if(e.async)x=null}};try{var h=x.abort;x.abort=function(){x&&h.call(x);
+g("abort")}}catch(l){}e.async&&e.timeout>0&&setTimeout(function(){x&&!E&&g("timeout")},e.timeout);try{x.send(n==="POST"||n==="PUT"||n==="DELETE"?e.data:null)}catch(m){c.handleError(e,x,null,m);d()}e.async||g();return x}},handleError:function(a,b,d,f){if(a.error)a.error.call(a.context||a,b,d,f);if(a.global)(a.context?c(a.context):c.event).trigger("ajaxError",[b,a,f])},active:0,httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status===
+1223||a.status===0}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),f=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(f)c.etag[b]=f;return a.status===304||a.status===0},httpData:function(a,b,d){var f=a.getResponseHeader("content-type")||"",e=b==="xml"||!b&&f.indexOf("xml")>=0;a=e?a.responseXML:a.responseText;e&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b===
+"json"||!b&&f.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&f.indexOf("javascript")>=0)c.globalEval(a);return a},param:function(a,b){function d(i,o){if(c.isArray(o))c.each(o,function(k,n){b||/\[\]$/.test(i)?f(i,n):d(i+"["+(typeof n==="object"||c.isArray(n)?k:"")+"]",n)});else!b&&o!=null&&typeof o==="object"?c.each(o,function(k,n){d(i+"["+k+"]",n)}):f(i,o)}function f(i,o){o=c.isFunction(o)?o():o;e[e.length]=encodeURIComponent(i)+"="+encodeURIComponent(o)}var e=[];if(b===w)b=c.ajaxSettings.traditional;
+if(c.isArray(a)||a.jquery)c.each(a,function(){f(this.name,this.value)});else for(var j in a)d(j,a[j]);return e.join("&").replace(yb,"+")}});var la={},Ab=/toggle|show|hide/,Bb=/^([+-]=)?([\d+-.]+)(.*)$/,W,va=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b){if(a||a===0)return this.animate(K("show",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");
+this[a].style.display=d||"";if(c.css(this[a],"display")==="none"){d=this[a].nodeName;var f;if(la[d])f=la[d];else{var e=c("<"+d+" />").appendTo("body");f=e.css("display");if(f==="none")f="block";e.remove();la[d]=f}c.data(this[a],"olddisplay",f)}}a=0;for(b=this.length;a<b;a++)this[a].style.display=c.data(this[a],"olddisplay")||"";return this}},hide:function(a,b){if(a||a===0)return this.animate(K("hide",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");!d&&d!=="none"&&c.data(this[a],
+"olddisplay",c.css(this[a],"display"))}a=0;for(b=this.length;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b){var d=typeof a==="boolean";if(c.isFunction(a)&&c.isFunction(b))this._toggle.apply(this,arguments);else a==null||d?this.each(function(){var f=d?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(K("toggle",3),a,b);return this},fadeTo:function(a,b,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d)},
+animate:function(a,b,d,f){var e=c.speed(b,d,f);if(c.isEmptyObject(a))return this.each(e.complete);return this[e.queue===false?"each":"queue"](function(){var j=c.extend({},e),i,o=this.nodeType===1&&c(this).is(":hidden"),k=this;for(i in a){var n=i.replace(ia,ja);if(i!==n){a[n]=a[i];delete a[i];i=n}if(a[i]==="hide"&&o||a[i]==="show"&&!o)return j.complete.call(this);if((i==="height"||i==="width")&&this.style){j.display=c.css(this,"display");j.overflow=this.style.overflow}if(c.isArray(a[i])){(j.specialEasing=
+j.specialEasing||{})[i]=a[i][1];a[i]=a[i][0]}}if(j.overflow!=null)this.style.overflow="hidden";j.curAnim=c.extend({},a);c.each(a,function(r,u){var z=new c.fx(k,j,r);if(Ab.test(u))z[u==="toggle"?o?"show":"hide":u](a);else{var C=Bb.exec(u),B=z.cur(true)||0;if(C){u=parseFloat(C[2]);var E=C[3]||"px";if(E!=="px"){k.style[r]=(u||1)+E;B=(u||1)/z.cur(true)*B;k.style[r]=B+E}if(C[1])u=(C[1]==="-="?-1:1)*u+B;z.custom(B,u,E)}else z.custom(B,u,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]);
+this.each(function(){for(var f=d.length-1;f>=0;f--)if(d[f].elem===this){b&&d[f](true);d.splice(f,1)}});b||this.dequeue();return this}});c.each({slideDown:K("show",1),slideUp:K("hide",1),slideToggle:K("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(a,b){c.fn[a]=function(d,f){return this.animate(b,d,f)}});c.extend({speed:function(a,b,d){var f=a&&typeof a==="object"?a:{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};f.duration=c.fx.off?0:typeof f.duration===
+"number"?f.duration:c.fx.speeds[f.duration]||c.fx.speeds._default;f.old=f.complete;f.complete=function(){f.queue!==false&&c(this).dequeue();c.isFunction(f.old)&&f.old.call(this)};return f},easing:{linear:function(a,b,d,f){return d+f*a},swing:function(a,b,d,f){return(-Math.cos(a*Math.PI)/2+0.5)*f+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]||
+c.fx.step._default)(this);if((this.prop==="height"||this.prop==="width")&&this.elem.style)this.elem.style.display="block"},cur:function(a){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];return(a=parseFloat(c.css(this.elem,this.prop,a)))&&a>-10000?a:parseFloat(c.curCSS(this.elem,this.prop))||0},custom:function(a,b,d){function f(j){return e.step(j)}this.startTime=J();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start;
+this.pos=this.state=0;var e=this;f.elem=this.elem;if(f()&&c.timers.push(f)&&!W)W=setInterval(c.fx.tick,13)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(a){var b=J(),d=true;if(a||b>=this.options.duration+this.startTime){this.now=
+this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var f in this.options.curAnim)if(this.options.curAnim[f]!==true)d=false;if(d){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;a=c.data(this.elem,"olddisplay");this.elem.style.display=a?a:this.options.display;if(c.css(this.elem,"display")==="none")this.elem.style.display="block"}this.options.hide&&c(this.elem).hide();if(this.options.hide||this.options.show)for(var e in this.options.curAnim)c.style(this.elem,
+e,this.options.orig[e]);this.options.complete.call(this.elem)}return false}else{e=b-this.startTime;this.state=e/this.options.duration;a=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||a](this.state,e,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a=c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||
+c.fx.stop()},stop:function(){clearInterval(W);W=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!=null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a===b.elem}).length};c.fn.offset="getBoundingClientRect"in s.documentElement?
+function(a){var b=this[0];if(a)return this.each(function(e){c.offset.setOffset(this,a,e)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);var d=b.getBoundingClientRect(),f=b.ownerDocument;b=f.body;f=f.documentElement;return{top:d.top+(self.pageYOffset||c.support.boxModel&&f.scrollTop||b.scrollTop)-(f.clientTop||b.clientTop||0),left:d.left+(self.pageXOffset||c.support.boxModel&&f.scrollLeft||b.scrollLeft)-(f.clientLeft||b.clientLeft||0)}}:function(a){var b=
+this[0];if(a)return this.each(function(r){c.offset.setOffset(this,a,r)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d=b.offsetParent,f=b,e=b.ownerDocument,j,i=e.documentElement,o=e.body;f=(e=e.defaultView)?e.getComputedStyle(b,null):b.currentStyle;for(var k=b.offsetTop,n=b.offsetLeft;(b=b.parentNode)&&b!==o&&b!==i;){if(c.offset.supportsFixedPosition&&f.position==="fixed")break;j=e?e.getComputedStyle(b,null):b.currentStyle;
+k-=b.scrollTop;n-=b.scrollLeft;if(b===d){k+=b.offsetTop;n+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(b.nodeName))){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=d;d=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&j.overflow!=="visible"){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=j}if(f.position==="relative"||f.position==="static"){k+=o.offsetTop;n+=o.offsetLeft}if(c.offset.supportsFixedPosition&&
+f.position==="fixed"){k+=Math.max(i.scrollTop,o.scrollTop);n+=Math.max(i.scrollLeft,o.scrollLeft)}return{top:k,left:n}};c.offset={initialize:function(){var a=s.body,b=s.createElement("div"),d,f,e,j=parseFloat(c.curCSS(a,"marginTop",true))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";
+a.insertBefore(b,a.firstChild);d=b.firstChild;f=d.firstChild;e=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=f.offsetTop!==5;this.doesAddBorderForTableAndCells=e.offsetTop===5;f.style.position="fixed";f.style.top="20px";this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15;f.style.position=f.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==j;a.removeChild(b);
+c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.curCSS(a,"marginTop",true))||0;d+=parseFloat(c.curCSS(a,"marginLeft",true))||0}return{top:b,left:d}},setOffset:function(a,b,d){if(/static/.test(c.curCSS(a,"position")))a.style.position="relative";var f=c(a),e=f.offset(),j=parseInt(c.curCSS(a,"top",true),10)||0,i=parseInt(c.curCSS(a,"left",true),10)||0;if(c.isFunction(b))b=b.call(a,
+d,e);d={top:b.top-e.top+j,left:b.left-e.left+i};"using"in b?b.using.call(a,d):f.css(d)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),f=/^body|html$/i.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.curCSS(a,"marginTop",true))||0;d.left-=parseFloat(c.curCSS(a,"marginLeft",true))||0;f.top+=parseFloat(c.curCSS(b[0],"borderTopWidth",true))||0;f.left+=parseFloat(c.curCSS(b[0],"borderLeftWidth",true))||0;return{top:d.top-
+f.top,left:d.left-f.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||s.body;a&&!/^body|html$/i.test(a.nodeName)&&c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(f){var e=this[0],j;if(!e)return null;if(f!==w)return this.each(function(){if(j=wa(this))j.scrollTo(!a?f:c(j).scrollLeft(),a?f:c(j).scrollTop());else this[d]=f});else return(j=wa(e))?"pageXOffset"in j?j[a?"pageYOffset":
+"pageXOffset"]:c.support.boxModel&&j.document.documentElement[d]||j.document.body[d]:e[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();c.fn["inner"+b]=function(){return this[0]?c.css(this[0],d,false,"padding"):null};c.fn["outer"+b]=function(f){return this[0]?c.css(this[0],d,false,f?"margin":"border"):null};c.fn[d]=function(f){var e=this[0];if(!e)return f==null?null:this;if(c.isFunction(f))return this.each(function(j){var i=c(this);i[d](f.call(this,j,i[d]()))});return"scrollTo"in
+e&&e.document?e.document.compatMode==="CSS1Compat"&&e.document.documentElement["client"+b]||e.document.body["client"+b]:e.nodeType===9?Math.max(e.documentElement["client"+b],e.body["scroll"+b],e.documentElement["scroll"+b],e.body["offset"+b],e.documentElement["offset"+b]):f===w?c.css(e,d):this.css(d,typeof f==="string"?f:f+"px")}});A.jQuery=A.$=c})(window);
diff --git a/src/content/js/showcase.js b/src/content/js/showcase.js
new file mode 100644
index 0000000..e9f5ce5
--- /dev/null
+++ b/src/content/js/showcase.js
@@ -0,0 +1,53 @@
+function get_current_page() {
+ return Math.round($('#apps').scrollLeft() / $('#apps').width());
+}
+
+function scroll_to_page(page, animate) {
+ var page_width = $('#apps').width();
+ var prev_page = get_current_page()
+ var attr = {'scrollLeft': page_width * page};
+ // Do the scrolling
+ if (animate) {
+ $('#apps').animate(attr, 300);
+ } else {
+ $('#apps').attr(attr);
+ }
+ $('.pager').each(function(index){
+ $(this).toggleClass('selected', index == page);
+ });
+}
+
+$(function () {
+ var w = $('#apps').width();
+
+ // don't run on the iPhone
+ if (w > 480) {
+ var page_control = $('<div></div>').attr('id','page_control');
+ var PADDING = 30;
+ $('.app').each(function(index) {
+ $(this).css({
+ 'position': 'absolute',
+ 'top': 0,
+ 'left': (w * index) + 'px',
+ 'width': (w - PADDING * 2) + 'px',
+ 'padding': PADDING + 'px',
+ });
+ var pager = $('<a></a>').attr('class','pager');
+ pager.attr('href','#!' + $(this).attr('id')).html($('h2 a', $(this)).html());
+ pager.click(function(){ scroll_to_page(index, true); });
+ page_control.append(pager);
+ });
+ $('#apps').css('overflow','hidden');
+ $('#showcase').prepend(page_control);
+ }
+ if (r = location.href.match('#!(.+)')) {
+ var app = $('#' + r[1]);
+ var index = $('.app').index(app);
+ if (index >= 0)
+ scroll_to_page(index, false);
+ else
+ scroll_to_page(0);
+ } else {
+ scroll_to_page(0);
+ }
+});
diff --git a/src/layouts/blog.rhtml b/src/layouts/blog.rhtml
new file mode 100644
index 0000000..6811319
--- /dev/null
+++ b/src/layouts/blog.rhtml
@@ -0,0 +1,94 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+ <head>
+ <meta name="viewport" content="width=device-width">
+ <meta http-equiv="Content-type" content="text/html; charset=utf-8">
+ <% if @item[:description] %>
+ <meta name="description" content="<%= @item[:description] %>">
+ <% end %>
+ <title>
+ Goo Software Blog - <%= @item[:title] %>
+ </title>
+ <link rel="alternate" type="application/atom+xml" title="Goo Software Blog" href="/blog.xml" />
+ <link rel="stylesheet" href="/css/blog.css" type="text/css" media="screen" charset="utf-8">
+ <script type="text/javascript" charset="utf-8" src="/js/google-analytics.js"></script>
+ <script type="text/javascript" charset="utf-8" src="/js/jquery-1.4.2.min.js"></script>
+ <% if @item[:js_imports] %>
+ <% for js in @item[:js_imports] %>
+ <script type="text/javascript" charset="utf-8" src="js/<%= js %>"></script>
+ <% end %>
+ <% end %>
+ </head>
+ <body>
+ <div id="main" class="blog">
+ <div id="header">
+ <a href="/"><img src="/images/goo-logo-333.png" id="logo" width="200" height="118" alt="Goo Logo" border="0" name="logo"></a>
+ <div id="slogan">
+ Thoughts on developing fantastic apps for iPhone, iPad and Android
+ </div>
+ </div>
+ <div id="sidebar">
+ <div class="subscribe">
+ <a href="/blog.xml">Subscribe</a>
+ </div>
+ <div>
+ <h2>Goo Software</h2>
+ <ul>
+ <li><a href="/">Goo home</a></li>
+ <li><a href="/blog/">Blog index</a></li>
+ </ul>
+ </div>
+ <div id="latest-posts">
+ <h2>Latest posts</h2>
+ <ul>
+ <% for a in sorted_articles[0,5] %>
+ <li><a href="<%= a.path %>" <%if @item.identifier == a.identifier%>class="selected"<%end%>><%= a[:title] %></a></li>
+ <% end %>
+ </ul>
+ </div>
+ </div>
+ <div id="content">
+ <h1><%= @item[:title] %></h1>
+ <div class="meta">
+ Posted <%= @item[:created_at] %> by <%= @item[:author_name] or @config[:author_name] %>
+ </div>
+ <div class="blog-content">
+ <%= yield %>
+ </div>
+ <div class="blog-nav">
+ <% index = sorted_articles.index(@item).to_i %>
+
+ <% if @item != sorted_articles.last then %>
+ <span class="nav previous">
+ ← <a href="<%= sorted_articles[index + 1].path %>"><%= sorted_articles[index + 1][:title]%></a>
+ </span>
+ <% end %>
+
+ <% if @item != sorted_articles.first then %>
+ <span class="nav next">
+ <a href="<%= sorted_articles[index-1].path %>"><%= sorted_articles[index-1][:title]%></a> →
+ </span>
+ <% end %>
+
+ </div>
+ <div class="comments">
+ <h2>Comments</h2>
+ <div id="disqus_thread"></div>
+ <script type="text/javascript">
+ /**
+ * var disqus_identifier; [Optional but recommended: Define a unique identifier (e.g. post id or slug) for this thread]
+ */
+ (function() {
+ var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
+ dsq.src = 'http://goosoftware.disqus.com/embed.js';
+ (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
+ })();
+ </script>
+ <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript=goosoftware">comments powered by Disqus.</a></noscript>
+ <a href="http://disqus.com" class="dsq-brlink">blog comments powered by <span class="logo-disqus">Disqus</span></a>
+ </div>
+ </div><!-- #content -->
+ <div style="clear:both"> </div>
+ </div><!-- #main -->
+ </body>
+</html>
diff --git a/src/layouts/goo.rhtml b/src/layouts/goo.rhtml
new file mode 100644
index 0000000..9cd109c
--- /dev/null
+++ b/src/layouts/goo.rhtml
@@ -0,0 +1,45 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+ <head>
+ <meta name="viewport" content="width=device-width">
+ <meta http-equiv="Content-type" content="text/html; charset=utf-8">
+ <% if @item[:description] %>
+ <meta name="description" content="<%= @item[:description] %>">
+ <% end %>
+ <title>
+ Goo Software - <%= @item[:title] %>
+ </title>
+ <link rel="stylesheet" href="/css/goo.css" type="text/css" media="screen" charset="utf-8">
+ <script type="text/javascript" charset="utf-8" src="/js/google-analytics.js"></script>
+ <script type="text/javascript" charset="utf-8" src="/js/jquery-1.4.2.min.js"></script>
+ <% if @item[:js_imports] %>
+ <% for js in @item[:js_imports] %>
+ <script type="text/javascript" charset="utf-8" src="js/<%= js %>"></script>
+ <% end %>
+ <% end %>
+ </head>
+ <body>
+ <div id="main">
+ <div id="header">
+ <a href="/"><img src="/images/goo-logo.png" id="logo" width="200" height="118" alt="Goo Logo" border="0" name="logo"></a>
+ <div id="slogan">
+ Fantastic apps for iPhone, iPad and Android
+ </div>
+ </div>
+ <div id="nav">
+ <ul class="tabs">
+ <% for nl in navlinks %>
+ <li>
+ <a <% if @item.identifier == nl[:url] %>class="selected"<% end %> href="<%= nl[:url] %>"><%= nl[:text] %></a>
+ </li>
+ <% end %>
+ </ul>
+ </div>
+ <%= yield %>
+ <div id="footer">
+ Goo Software Ltd, registered in England and Wales with company number 7242280.
+ Registered address: 88 Lucerne Avenue, Bicester OX26 3EL, UK
+ </div>
+ </div><!-- #main -->
+ </body>
+</html>
diff --git a/src/lib/default.rb b/src/lib/default.rb
new file mode 100644
index 0000000..4c9879a
--- /dev/null
+++ b/src/lib/default.rb
@@ -0,0 +1,4 @@
+# All files in the 'lib' directory will be loaded
+# before nanoc starts compiling.
+
+include Nanoc3::Helpers::Blogging
\ No newline at end of file
diff --git a/src/lib/navlinks.rb b/src/lib/navlinks.rb
new file mode 100644
index 0000000..38cbdb2
--- /dev/null
+++ b/src/lib/navlinks.rb
@@ -0,0 +1,9 @@
+def navlinks
+ return [
+ { :text => "Home", :url => "/" },
+ { :text => "Contact", :url => "/contact/" },
+ { :text => "About", :url => "/about/" },
+ { :text => "Help", :url => "/help/" },
+ { :text => "Blog", :url => "/blog/" },
+ ]
+end
\ No newline at end of file
diff --git a/src/lib/string_additions.rb b/src/lib/string_additions.rb
new file mode 100644
index 0000000..17c2bf3
--- /dev/null
+++ b/src/lib/string_additions.rb
@@ -0,0 +1,42 @@
+class String
+ # to_slug found at http://github.com/ludo/to_slug/blob/master/lib/to_slug.rb
+ #
+ # Generate a slug for the string +value+.
+ #
+ # A slug should consist of numbers (0-9), lowercase letters (a-z) and
+ # dashes (-). Any other characters should be filtered.
+ #
+ # ==== Example
+ #
+ # "The World is Beautiful!".to_slug # => "the-world-is-beautiful"
+ #
+ # ==== Returns
+ # String:: A 'sluggified' version of this string
+ #
+ # --
+ # @api public
+ def to_slug
+ # Perform transliteration to replace non-ascii characters with an ascii
+ # character
+ value = self.gsub(/[^\x00-\x7F]/n, '').to_s
+
+ # Remove single quotes from input
+ value.gsub!(/[']+/, '')
+
+ # Replace any non-word character (\W) with a space
+ value.gsub!(/\W+/, ' ')
+
+ # Remove any whitespace before and after the string
+ value.strip!
+
+ # All characters should be downcased
+ value.downcase!
+
+ # Replace spaces with dashes
+ value.gsub!(' ', '-')
+
+ # Return the resulting slug
+ value
+ end
+
+end
\ No newline at end of file
|
blazingcloud/pie
|
15f9b5c3b6f245f1771bbefc9956165eef6ea927
|
put back tests for places accessor, move book use case failures to pivotal tracker
|
diff --git a/lib/place.rb b/lib/place.rb
index b4e0e0a..7410fd8 100644
--- a/lib/place.rb
+++ b/lib/place.rb
@@ -1,86 +1,87 @@
class Pie::Place
- attr_reader :name, :description, :paths
+ attr_accessor :description
+ attr_reader :name, :paths
def initialize(places, options)
@paths = {}
@places = places
extract_standard_options(options)
extract_name_and_description(options)
@places[@name] = self
end
def to_s
@name
end
def path(nodes)
nodes.each do |place_name, direction|
place = @places[place_name]
raise "#{place_name} is not a place" if place.nil?
@paths[place_name] = direction
@places[place_name].paths[name] = direction.opposite unless !direction.respond_to?(:dead_end?) || direction.dead_end?
end
end
private
def extract_name_and_description(options)
raise "You seem to have extras option in this place!" unless options.length == 1
self.name = options.keys.first
@description = options.values.first
end
def extract_standard_options(options)
end
-
+
def name=(name)
valid = false
begin
result = eval name.to_s
# if there is no exception, it's a problem like String or something Ruby knows
rescue NameError
# this is what we want, so that method_missing will be called if we use this as a place name
valid = true
rescue SyntaxError => e
msg = case e.message
when /syntax error, unexpected \$end/
"#{e.message}\n"+
"Sorry, You can't name a place 'class' "+
"because Ruby was expecting you to define a 'class' "+
"which is always followed by an 'end'"
when /syntax error, unexpected keyword/
"#{e.message}\nSorry, you can't name a place with a Ruby keyword, like '#{name}'"
else
# don't have an example where this happens, but I would guess there is one
"#{e.message}\nSorry, Ruby doesn't think that '#{name}' makes sense as the name of a place."
end
raise e.class, msg
rescue ArgumentError => e
msg = "#{e.message}\n"+
"You probably weren't trying to argue with Ruby, but it recognized '#{name}' and expected it to be followed by "+
"some more input, which it calls 'arguments'. Sorry '#{name}' can't be a place name."
raise e.class, msg
rescue Exception => e
# other kinds of inappropriate names
msg = "#{e.message}\nSorry, you can't name a place with something like '#{name}'"
raise e.class, msg
end
if !valid
raise("Sorry, you can't name a place with a name that Ruby already knows like '#{name}'")
end
@name = name
end
end
diff --git a/spec/pie_spec.rb b/spec/pie_spec.rb
index ff9f80e..ee6f55a 100644
--- a/spec/pie_spec.rb
+++ b/spec/pie_spec.rb
@@ -1,247 +1,222 @@
require File.join(File.expand_path(File.dirname(__FILE__)), "..", "lib", "pie")
class Game
include Pie
def get_binding
binding
end
end
describe "baking pie" do
before do
@game = Game.new
end
describe "included in a class" do
it "can access the current_place" do
@game.instance_eval do
current_place.should == nil
place ship:"this is a ship"
current_place(:ship)
current_place.should == ship
place land:"this is land"
current_place('land')
current_place.should == land
end
end
end
describe "with template" do
it "has a default template" do
@game.template.should == :image_page
end
it "can set an alternate template" do
@game.instance_eval do
template :foo
template.should == :foo
end
end
end
describe "image declaration" do
it "can declare an image" do
@game.instance_eval do
image ship:"http://foo.com/ship.png"
images[:ship].should == "http://foo.com/ship.png"
end
end
it "can declare multiple image statements" do
@game.instance_eval do
image ship:"http://foo.com/ship.png"
image basket:"http://foo.com/basket.png"
images[:ship].should == "http://foo.com/ship.png"
images[:basket].should == "http://foo.com/basket.png"
end
end
it "can declare multiple images with one statement" do
@game.instance_eval do
image ship:"http://foo.com/ship.png",
basket:"http://foo.com/basket.png"
images[:ship].should == "http://foo.com/ship.png"
images[:basket].should == "http://foo.com/basket.png"
end
end
end
describe "creates places" do
it "raises an error when extra options are given" do
lambda {
@game.place ship:"this is a ship", extra_option:"this"
}.should raise_error
end
it "can have a description" do
@game.instance_eval do
place ship:"this is a ship"
ship.class.should == Place
ship.name.should == :ship
ship.description.should == "this is a ship"
end
end
it "doesn't contain places from other games" do
@game.instance_eval do
place ship:"this is a ship"
end
@game2 = Game.new
@game2.instance_eval do
place boat:"this is a boat"
end
puts @game.places.inspect
puts @game2.places.inspect
@game2.places.length.should == 1
end
describe "gives an appropriate error" do
it "when specifying a path from a place that does not exist" do
lambda {
@game.instance_eval do
place boat:"this is a boat"
something.path boat:north
end
}.should raise_error(NoMethodError, "NoMethodError: Pie was expecting a place named 'something', but we've only got places named: boat")
end
it "when a place is named with a Ruby keyword, like 'end'" do
lambda {
@game.instance_eval do
place end:"This is where it all ends."
end
}.should raise_error(SyntaxError, "(eval):1: syntax error, unexpected keyword_end\nSorry, you can't name a place with a Ruby keyword, like 'end'")
end
it "when using eval and binding and a place is named with a Ruby keyword, like 'end'" do
lambda {
eval("template :game_screen\nplace end:\"This is where it all ends.\"", @game.get_binding)
}.should raise_error(SyntaxError, "(eval):1: syntax error, unexpected keyword_end\nSorry, you can't name a place with a Ruby keyword, like 'end'")
end
it "when a place is named with a Ruby keyword, like 'do'" do
lambda {
@game.instance_eval do
place do:"Don't step in this."
end
}.should raise_error(SyntaxError, "(eval):1: syntax error, unexpected keyword_do_block\nSorry, you can't name a place with a Ruby keyword, like 'do'")
end
it "when a place is named with a Ruby keyword, like 'class'" do
lambda {
@game.instance_eval do
place class:"This is a place in school."
end
}.should raise_error(SyntaxError, "(eval):1: syntax error, unexpected $end\nclass\n ^\n"+
"Sorry, You can't name a place 'class' because Ruby was expecting you to define a 'class' which is always followed by an 'end'")
end
it "when a place is named with a Ruby method, like 'eval'" do
lambda {
@game.instance_eval do
place eval:"Now you're playing with fire."
end
}.should raise_error(ArgumentError, "wrong number of arguments (0 for 1..4)\n" +
"You probably weren't trying to argue with Ruby, but it recognized 'eval' and expected it to be followed by "+
"some more input, which it calls 'arguments'. Sorry 'eval' can't be a place name.")
end
it "when a place is named with a built-in class" do
lambda {
@game.instance_eval do
place String:"This is a really long place made of yarn."
end
}.should raise_error(Exception, "Sorry, you can't name a place with a name that Ruby already knows like 'String'")
end
end
describe "with paths" do
before do
@game.instance_eval do
place field:"You are in a large, grassy field. You see many trees to the north and a path to the east"
place forest:"It is dark in the forest"
place cliff_top:"The path ends at the top of a steep cliff"
place cliff_bottom:"You walked off the cliff and fell to your death"
end
end
it "should have links between two places" do
@game.instance_eval do
field.path forest:north
field.paths.should == {forest:north}
forest.paths.should == {field:south}
end
end
it "should have one way links" do
@game.instance_eval do
cliff_top.path cliff_bottom:east!
cliff_top.paths.should == {cliff_bottom:east}
cliff_bottom.paths.should == {}
end
end
it "should support simple strings" do
@game.instance_eval do
field.path cliff_bottom:"flying leap"
field.paths[:cliff_bottom].should == "flying leap"
end
end
- it "raises an error when place doesn't exist" do
+ it "raises an error when non-existant place speficied in path" do
lambda {
@game.instance_eval do
field.path xxx:north
end
}.should raise_error(Exception, "xxx is not a place")
end
end
end
- # describe "can access places" do
- # before do
- # ship description:"ookina fune"
- # building description:"ookina biru"
- # tower description:"ookina towa"
- # end
- #
- # it "which are accessible by named key (symbol)" do
- # ship = $pie.places[:ship]
- # ship.should_not be_nil
- # ship[:description].should == "ookina fune"
- # end
- #
- # it "which are accessible by named key (string)" do
- # ship = $pie.places["ship"]
- # ship.should_not be_nil
- # ship[:description].should == "ookina fune"
- # end
- #
- # it "resulting in 2 places" do
- # $pie.places.length.should == 3
- # end
- #
- # it "and can find place after named place" do
- # building = $pie.places.after(:ship)
- # building.should_not be_nil
- # building[:description].should == "ookina biru"
- # end
- #
- # it "and finds nil after last place" do
- # nothing = $pie.places.after(:tower)
- # nothing.should be_nil
- # end
- #
- # it "and can find place before named place" do
- # building = $pie.places.before(:tower)
- # building.should_not be_nil
- # building[:description].should == "ookina biru"
- # end
- #
- # it "and finds nil before first place" do
- # nothing = $pie.places.before(:ship)
- # nothing.should be_nil
- # end
- # end
+ describe "can access places" do
+ before do
+ @game.instance_eval do
+ place ship:"ookina fune"
+ place building:"ookina biru"
+ place tower:"ookina towa"
+ end
+ end
+
+ it "which are accessible by named key (symbol)" do
+ ship = @game.places[:ship]
+ ship.should_not be_nil
+ ship.description.should == "ookina fune"
+ end
+
+ it "resulting in 2 places" do
+ @game.places.length.should == 3
+ end
+
+ end
end
|
blazingcloud/pie
|
10e030f8f2a5821cbec2e16f6eb51f81346c1b1e
|
display real Ruby error also for 'NoMethodError'
|
diff --git a/lib/pie.rb b/lib/pie.rb
index a605c3f..3cb2fea 100644
--- a/lib/pie.rb
+++ b/lib/pie.rb
@@ -1,86 +1,86 @@
module Pie
attr_accessor :places
def initialize
@places = {}
end
def self.[](key)
(@map ||= {})[key]
end
def self.[]=(key, value)
(@map ||= {})[key] = value
end
def self.language=(language)
@language = language
end
def self.localized(id)
@values ||= {
:japanese => {
:go_north => "Go North (in jp!)",
:go_south => "Go South (in jp!)",
:go_east => "Go East (in jp!)",
:go_west => "Go West (in jp!)"
},
:english => {
:go_north => "Go North",
:go_south => "Go South",
:go_east => "Go East",
:go_west => "Go West"
}
}
@values[@language || :english][id]
end
def self.places
Pie[:places] ||= {}
end
def template(name = nil)
if name
Pie[:template] = name.to_sym
else
Pie[:template] || :image_page
end
end
def images
Pie[:images] ||= {}
end
def image(image_maps)
images.merge!(image_maps)
end
def place(options)
Place.new(places, options)
end
def method_missing name
place = places[name.to_sym]
- raise NoMethodError, "Pie was expecting a place named '#{name}', but we've only got places named: #{places.keys.join(', ')}" if place.nil?
+ raise NoMethodError, "NoMethodError: Pie was expecting a place named '#{name}', but we've only got places named: #{places.keys.join(', ')}" if place.nil?
place
end
def current_place(name=nil)
if name
Pie[:current_place] = places[name.to_sym]
else
Pie[:current_place]
end
end
def current_image
images[current_place.name] if current_place
end
def language(language)
Pie.language = language
end
end
require 'place'
require 'direction'
diff --git a/pie.gemspec b/pie.gemspec
index a56b663..1efad86 100644
--- a/pie.gemspec
+++ b/pie.gemspec
@@ -1,11 +1,11 @@
spec = Gem::Specification.new do |s|
s.name = 'pie'
s.authors = 'Sarah Allen, Sarah Mei, Rich Kilmer'
s.homepage = 'http://github.com/blazingcloud/pie'
- s.version = '0.2.12'
+ s.version = '0.2.13'
s.summary = 'Pie, a language for developing games and books'
s.files = Dir['lib/*.rb']+Dir['views/*.erb']+['README.md', 'MIT-LICENSE.txt', 'bin/pie']
s.bindir = 'bin'
s.executables << 'pie'
end
diff --git a/spec/pie_spec.rb b/spec/pie_spec.rb
index f17f093..ff9f80e 100644
--- a/spec/pie_spec.rb
+++ b/spec/pie_spec.rb
@@ -1,247 +1,247 @@
require File.join(File.expand_path(File.dirname(__FILE__)), "..", "lib", "pie")
class Game
include Pie
def get_binding
binding
end
end
describe "baking pie" do
before do
@game = Game.new
end
describe "included in a class" do
it "can access the current_place" do
@game.instance_eval do
current_place.should == nil
place ship:"this is a ship"
current_place(:ship)
current_place.should == ship
place land:"this is land"
current_place('land')
current_place.should == land
end
end
end
describe "with template" do
it "has a default template" do
@game.template.should == :image_page
end
it "can set an alternate template" do
@game.instance_eval do
template :foo
template.should == :foo
end
end
end
describe "image declaration" do
it "can declare an image" do
@game.instance_eval do
image ship:"http://foo.com/ship.png"
images[:ship].should == "http://foo.com/ship.png"
end
end
it "can declare multiple image statements" do
@game.instance_eval do
image ship:"http://foo.com/ship.png"
image basket:"http://foo.com/basket.png"
images[:ship].should == "http://foo.com/ship.png"
images[:basket].should == "http://foo.com/basket.png"
end
end
it "can declare multiple images with one statement" do
@game.instance_eval do
image ship:"http://foo.com/ship.png",
basket:"http://foo.com/basket.png"
images[:ship].should == "http://foo.com/ship.png"
images[:basket].should == "http://foo.com/basket.png"
end
end
end
describe "creates places" do
it "raises an error when extra options are given" do
lambda {
@game.place ship:"this is a ship", extra_option:"this"
}.should raise_error
end
it "can have a description" do
@game.instance_eval do
place ship:"this is a ship"
ship.class.should == Place
ship.name.should == :ship
ship.description.should == "this is a ship"
end
end
it "doesn't contain places from other games" do
@game.instance_eval do
place ship:"this is a ship"
end
@game2 = Game.new
@game2.instance_eval do
place boat:"this is a boat"
end
puts @game.places.inspect
puts @game2.places.inspect
@game2.places.length.should == 1
end
describe "gives an appropriate error" do
it "when specifying a path from a place that does not exist" do
lambda {
@game.instance_eval do
place boat:"this is a boat"
something.path boat:north
end
- }.should raise_error(SyntaxError, "#<NoMethodError: Pie was expecting a place named 'something', but we've only got places named: boat")
+ }.should raise_error(NoMethodError, "NoMethodError: Pie was expecting a place named 'something', but we've only got places named: boat")
end
it "when a place is named with a Ruby keyword, like 'end'" do
lambda {
@game.instance_eval do
place end:"This is where it all ends."
end
}.should raise_error(SyntaxError, "(eval):1: syntax error, unexpected keyword_end\nSorry, you can't name a place with a Ruby keyword, like 'end'")
end
it "when using eval and binding and a place is named with a Ruby keyword, like 'end'" do
lambda {
eval("template :game_screen\nplace end:\"This is where it all ends.\"", @game.get_binding)
}.should raise_error(SyntaxError, "(eval):1: syntax error, unexpected keyword_end\nSorry, you can't name a place with a Ruby keyword, like 'end'")
end
it "when a place is named with a Ruby keyword, like 'do'" do
lambda {
@game.instance_eval do
place do:"Don't step in this."
end
}.should raise_error(SyntaxError, "(eval):1: syntax error, unexpected keyword_do_block\nSorry, you can't name a place with a Ruby keyword, like 'do'")
end
it "when a place is named with a Ruby keyword, like 'class'" do
lambda {
@game.instance_eval do
place class:"This is a place in school."
end
}.should raise_error(SyntaxError, "(eval):1: syntax error, unexpected $end\nclass\n ^\n"+
"Sorry, You can't name a place 'class' because Ruby was expecting you to define a 'class' which is always followed by an 'end'")
end
it "when a place is named with a Ruby method, like 'eval'" do
lambda {
@game.instance_eval do
place eval:"Now you're playing with fire."
end
}.should raise_error(ArgumentError, "wrong number of arguments (0 for 1..4)\n" +
"You probably weren't trying to argue with Ruby, but it recognized 'eval' and expected it to be followed by "+
"some more input, which it calls 'arguments'. Sorry 'eval' can't be a place name.")
end
it "when a place is named with a built-in class" do
lambda {
@game.instance_eval do
place String:"This is a really long place made of yarn."
end
}.should raise_error(Exception, "Sorry, you can't name a place with a name that Ruby already knows like 'String'")
end
end
describe "with paths" do
before do
@game.instance_eval do
place field:"You are in a large, grassy field. You see many trees to the north and a path to the east"
place forest:"It is dark in the forest"
place cliff_top:"The path ends at the top of a steep cliff"
place cliff_bottom:"You walked off the cliff and fell to your death"
end
end
it "should have links between two places" do
@game.instance_eval do
field.path forest:north
field.paths.should == {forest:north}
forest.paths.should == {field:south}
end
end
it "should have one way links" do
@game.instance_eval do
cliff_top.path cliff_bottom:east!
cliff_top.paths.should == {cliff_bottom:east}
cliff_bottom.paths.should == {}
end
end
it "should support simple strings" do
@game.instance_eval do
field.path cliff_bottom:"flying leap"
field.paths[:cliff_bottom].should == "flying leap"
end
end
it "raises an error when place doesn't exist" do
lambda {
@game.instance_eval do
field.path xxx:north
end
}.should raise_error(Exception, "xxx is not a place")
end
end
end
# describe "can access places" do
# before do
# ship description:"ookina fune"
# building description:"ookina biru"
# tower description:"ookina towa"
# end
#
# it "which are accessible by named key (symbol)" do
# ship = $pie.places[:ship]
# ship.should_not be_nil
# ship[:description].should == "ookina fune"
# end
#
# it "which are accessible by named key (string)" do
# ship = $pie.places["ship"]
# ship.should_not be_nil
# ship[:description].should == "ookina fune"
# end
#
# it "resulting in 2 places" do
# $pie.places.length.should == 3
# end
#
# it "and can find place after named place" do
# building = $pie.places.after(:ship)
# building.should_not be_nil
# building[:description].should == "ookina biru"
# end
#
# it "and finds nil after last place" do
# nothing = $pie.places.after(:tower)
# nothing.should be_nil
# end
#
# it "and can find place before named place" do
# building = $pie.places.before(:tower)
# building.should_not be_nil
# building[:description].should == "ookina biru"
# end
#
# it "and finds nil before first place" do
# nothing = $pie.places.before(:ship)
# nothing.should be_nil
# end
# end
end
|
blazingcloud/pie
|
f5d784bea7090659dae23f4061dfa1b03d771b14
|
better description for NoMethodError
|
diff --git a/lib/pie.rb b/lib/pie.rb
index 69fbd6b..a605c3f 100644
--- a/lib/pie.rb
+++ b/lib/pie.rb
@@ -1,86 +1,86 @@
module Pie
attr_accessor :places
def initialize
@places = {}
end
def self.[](key)
(@map ||= {})[key]
end
def self.[]=(key, value)
(@map ||= {})[key] = value
end
def self.language=(language)
@language = language
end
def self.localized(id)
@values ||= {
:japanese => {
:go_north => "Go North (in jp!)",
:go_south => "Go South (in jp!)",
:go_east => "Go East (in jp!)",
:go_west => "Go West (in jp!)"
},
:english => {
:go_north => "Go North",
:go_south => "Go South",
:go_east => "Go East",
:go_west => "Go West"
}
}
@values[@language || :english][id]
end
def self.places
Pie[:places] ||= {}
end
def template(name = nil)
if name
Pie[:template] = name.to_sym
else
Pie[:template] || :image_page
end
end
def images
Pie[:images] ||= {}
end
def image(image_maps)
images.merge!(image_maps)
end
def place(options)
Place.new(places, options)
end
def method_missing name
place = places[name.to_sym]
- raise NoMethodError if place.nil?
+ raise NoMethodError, "Pie was expecting a place named '#{name}', but we've only got places named: #{places.keys.join(', ')}" if place.nil?
place
end
def current_place(name=nil)
if name
Pie[:current_place] = places[name.to_sym]
else
Pie[:current_place]
end
end
def current_image
images[current_place.name] if current_place
end
def language(language)
Pie.language = language
end
end
require 'place'
require 'direction'
diff --git a/spec/pie_spec.rb b/spec/pie_spec.rb
index cff8334..f17f093 100644
--- a/spec/pie_spec.rb
+++ b/spec/pie_spec.rb
@@ -1,227 +1,247 @@
require File.join(File.expand_path(File.dirname(__FILE__)), "..", "lib", "pie")
class Game
include Pie
+
+ def get_binding
+ binding
+ end
end
describe "baking pie" do
before do
@game = Game.new
end
describe "included in a class" do
it "can access the current_place" do
@game.instance_eval do
current_place.should == nil
place ship:"this is a ship"
current_place(:ship)
current_place.should == ship
place land:"this is land"
current_place('land')
current_place.should == land
end
end
end
describe "with template" do
it "has a default template" do
@game.template.should == :image_page
end
it "can set an alternate template" do
@game.instance_eval do
template :foo
template.should == :foo
end
end
end
describe "image declaration" do
it "can declare an image" do
@game.instance_eval do
image ship:"http://foo.com/ship.png"
images[:ship].should == "http://foo.com/ship.png"
end
end
it "can declare multiple image statements" do
@game.instance_eval do
image ship:"http://foo.com/ship.png"
image basket:"http://foo.com/basket.png"
images[:ship].should == "http://foo.com/ship.png"
images[:basket].should == "http://foo.com/basket.png"
end
end
it "can declare multiple images with one statement" do
@game.instance_eval do
image ship:"http://foo.com/ship.png",
basket:"http://foo.com/basket.png"
images[:ship].should == "http://foo.com/ship.png"
images[:basket].should == "http://foo.com/basket.png"
end
end
end
describe "creates places" do
it "raises an error when extra options are given" do
lambda {
@game.place ship:"this is a ship", extra_option:"this"
}.should raise_error
end
it "can have a description" do
@game.instance_eval do
place ship:"this is a ship"
ship.class.should == Place
ship.name.should == :ship
ship.description.should == "this is a ship"
end
end
it "doesn't contain places from other games" do
@game.instance_eval do
place ship:"this is a ship"
end
@game2 = Game.new
@game2.instance_eval do
place boat:"this is a boat"
end
puts @game.places.inspect
puts @game2.places.inspect
@game2.places.length.should == 1
end
describe "gives an appropriate error" do
+ it "when specifying a path from a place that does not exist" do
+ lambda {
+ @game.instance_eval do
+ place boat:"this is a boat"
+ something.path boat:north
+ end
+ }.should raise_error(SyntaxError, "#<NoMethodError: Pie was expecting a place named 'something', but we've only got places named: boat")
+
+ end
+
it "when a place is named with a Ruby keyword, like 'end'" do
lambda {
@game.instance_eval do
place end:"This is where it all ends."
end
}.should raise_error(SyntaxError, "(eval):1: syntax error, unexpected keyword_end\nSorry, you can't name a place with a Ruby keyword, like 'end'")
end
-
+
+ it "when using eval and binding and a place is named with a Ruby keyword, like 'end'" do
+ lambda {
+ eval("template :game_screen\nplace end:\"This is where it all ends.\"", @game.get_binding)
+ }.should raise_error(SyntaxError, "(eval):1: syntax error, unexpected keyword_end\nSorry, you can't name a place with a Ruby keyword, like 'end'")
+ end
+
it "when a place is named with a Ruby keyword, like 'do'" do
lambda {
@game.instance_eval do
place do:"Don't step in this."
end
}.should raise_error(SyntaxError, "(eval):1: syntax error, unexpected keyword_do_block\nSorry, you can't name a place with a Ruby keyword, like 'do'")
end
it "when a place is named with a Ruby keyword, like 'class'" do
lambda {
@game.instance_eval do
place class:"This is a place in school."
end
}.should raise_error(SyntaxError, "(eval):1: syntax error, unexpected $end\nclass\n ^\n"+
"Sorry, You can't name a place 'class' because Ruby was expecting you to define a 'class' which is always followed by an 'end'")
end
it "when a place is named with a Ruby method, like 'eval'" do
lambda {
@game.instance_eval do
place eval:"Now you're playing with fire."
end
}.should raise_error(ArgumentError, "wrong number of arguments (0 for 1..4)\n" +
"You probably weren't trying to argue with Ruby, but it recognized 'eval' and expected it to be followed by "+
"some more input, which it calls 'arguments'. Sorry 'eval' can't be a place name.")
end
it "when a place is named with a built-in class" do
lambda {
@game.instance_eval do
place String:"This is a really long place made of yarn."
end
}.should raise_error(Exception, "Sorry, you can't name a place with a name that Ruby already knows like 'String'")
end
end
describe "with paths" do
before do
@game.instance_eval do
place field:"You are in a large, grassy field. You see many trees to the north and a path to the east"
place forest:"It is dark in the forest"
place cliff_top:"The path ends at the top of a steep cliff"
place cliff_bottom:"You walked off the cliff and fell to your death"
end
end
it "should have links between two places" do
@game.instance_eval do
field.path forest:north
field.paths.should == {forest:north}
forest.paths.should == {field:south}
end
end
it "should have one way links" do
@game.instance_eval do
cliff_top.path cliff_bottom:east!
cliff_top.paths.should == {cliff_bottom:east}
cliff_bottom.paths.should == {}
end
end
it "should support simple strings" do
@game.instance_eval do
field.path cliff_bottom:"flying leap"
field.paths[:cliff_bottom].should == "flying leap"
end
end
it "raises an error when place doesn't exist" do
lambda {
@game.instance_eval do
field.path xxx:north
end
}.should raise_error(Exception, "xxx is not a place")
end
end
end
# describe "can access places" do
# before do
# ship description:"ookina fune"
# building description:"ookina biru"
# tower description:"ookina towa"
# end
#
# it "which are accessible by named key (symbol)" do
# ship = $pie.places[:ship]
# ship.should_not be_nil
# ship[:description].should == "ookina fune"
# end
#
# it "which are accessible by named key (string)" do
# ship = $pie.places["ship"]
# ship.should_not be_nil
# ship[:description].should == "ookina fune"
# end
#
# it "resulting in 2 places" do
# $pie.places.length.should == 3
# end
#
# it "and can find place after named place" do
# building = $pie.places.after(:ship)
# building.should_not be_nil
# building[:description].should == "ookina biru"
# end
#
# it "and finds nil after last place" do
# nothing = $pie.places.after(:tower)
# nothing.should be_nil
# end
#
# it "and can find place before named place" do
# building = $pie.places.before(:tower)
# building.should_not be_nil
# building[:description].should == "ookina biru"
# end
#
# it "and finds nil before first place" do
# nothing = $pie.places.before(:ship)
# nothing.should be_nil
# end
# end
end
|
blazingcloud/pie
|
1378d2aad42438fe19189b33fee4f957dd7051d9
|
remove test file
|
diff --git a/lib/place.rb b/lib/place.rb
index 16a3259..b4e0e0a 100644
--- a/lib/place.rb
+++ b/lib/place.rb
@@ -1,88 +1,86 @@
-#require_relative 'pie.rb'
-
class Pie::Place
attr_reader :name, :description, :paths
def initialize(places, options)
@paths = {}
@places = places
extract_standard_options(options)
extract_name_and_description(options)
@places[@name] = self
end
def to_s
@name
end
def path(nodes)
nodes.each do |place_name, direction|
place = @places[place_name]
raise "#{place_name} is not a place" if place.nil?
@paths[place_name] = direction
@places[place_name].paths[name] = direction.opposite unless !direction.respond_to?(:dead_end?) || direction.dead_end?
end
end
private
def extract_name_and_description(options)
raise "You seem to have extras option in this place!" unless options.length == 1
self.name = options.keys.first
@description = options.values.first
end
def extract_standard_options(options)
end
def name=(name)
valid = false
begin
result = eval name.to_s
# if there is no exception, it's a problem like String or something Ruby knows
rescue NameError
# this is what we want, so that method_missing will be called if we use this as a place name
valid = true
rescue SyntaxError => e
msg = case e.message
when /syntax error, unexpected \$end/
"#{e.message}\n"+
"Sorry, You can't name a place 'class' "+
"because Ruby was expecting you to define a 'class' "+
"which is always followed by an 'end'"
when /syntax error, unexpected keyword/
"#{e.message}\nSorry, you can't name a place with a Ruby keyword, like '#{name}'"
else
# don't have an example where this happens, but I would guess there is one
"#{e.message}\nSorry, Ruby doesn't think that '#{name}' makes sense as the name of a place."
end
raise e.class, msg
rescue ArgumentError => e
msg = "#{e.message}\n"+
"You probably weren't trying to argue with Ruby, but it recognized '#{name}' and expected it to be followed by "+
"some more input, which it calls 'arguments'. Sorry '#{name}' can't be a place name."
raise e.class, msg
rescue Exception => e
# other kinds of inappropriate names
msg = "#{e.message}\nSorry, you can't name a place with something like '#{name}'"
raise e.class, msg
end
if !valid
raise("Sorry, you can't name a place with a name that Ruby already knows like '#{name}'")
end
@name = name
end
end
diff --git a/lib/test.rb b/lib/test.rb
deleted file mode 100644
index a9a258f..0000000
--- a/lib/test.rb
+++ /dev/null
@@ -1,23 +0,0 @@
-class Foo
- attr_reader :bar
-
- def initialize(value)
- puts "initialize value= #{value}"
- setup(value)
- end
-
- def bar=(value)
- puts "bar= value= #{value}"
- raise Exception, "5 not allowed" if value == 5
- @bar = value
- end
-
- def setup(value)
- puts "setup value= #{value}, #{self}"
- self.bar=value
- end
-private
-
-
-
-end
|
blazingcloud/pie
|
f4d25c6d4c33fb365a48f26dc4f46ff9e393e9e1
|
refactor name validation to handle logical alternate cases
|
diff --git a/README.md b/README.md
index 2d2df71..b0a4eab 100644
--- a/README.md
+++ b/README.md
@@ -1,64 +1,65 @@
# Pie
A game development DSL, inspired by Yasuko Ohba's Ruby Kaigi talk and a late night conversation with @knowtheory, @wycats, @sarahmei and @ultrasaurus.
Pie requires Ruby 1.9, because it is so cool.
## Examples
### Game
pie game.pie
then go to:
http://localhost:31415/park
Follow links to wander around the game world. Yes, that is all there is right now.
### Book -- NOT WORKING YET
There is a sample in book.rb. To use it:
pie book.pie
then go to:
http://localhost:31415/ship
http://localhost:31415/building
http://localhost:31415/tower
Someday there will be UI to change pages.
## Issues?
Bugs and features are tracked here: http://www.pivotaltracker.com/projects/115060
If you are trying to develop a game or a book using pie and have a question, ask in the [pie dev group](http://groups.google.com/group/pie-dev)
## If you want to help improve pie itself...
I want to try to resist adding any new features until we have no bugs and kid-friendly error messages. Help is welcome. Feel free to fork and submit pull requests or join the google group http://groups.google.com/group/pie-cooks
Sarah's talk on the making of pie: [slides](http://www.slideshare.net/sarah.allen/the-making-of-pie)
## Pie Contributors
Core team (in order of appearance)
* Sarah Allen @ultrasaurs
* Sarah Mei @sarahmei
* Rich Kilmer @richkilmer
Contributors
+* Sean Durham
* Matthew Bass @pelargir
* Dan Steinicke
* Akira Matsuda
* Chad Fowler
## Related Projects
* [hosted IDE](http://pie-bakery.heroku.com) ([source code](https://github.com/blazingcloud/pie-bakery))
* [mobile-pie](https://github.com/blazingcloud/mobile-pie)
diff --git a/pie.gemspec b/pie.gemspec
index d8d5d09..a56b663 100644
--- a/pie.gemspec
+++ b/pie.gemspec
@@ -1,11 +1,11 @@
spec = Gem::Specification.new do |s|
s.name = 'pie'
s.authors = 'Sarah Allen, Sarah Mei, Rich Kilmer'
s.homepage = 'http://github.com/blazingcloud/pie'
- s.version = '0.2.11'
+ s.version = '0.2.12'
s.summary = 'Pie, a language for developing games and books'
s.files = Dir['lib/*.rb']+Dir['views/*.erb']+['README.md', 'MIT-LICENSE.txt', 'bin/pie']
s.bindir = 'bin'
s.executables << 'pie'
end
|
blazingcloud/pie
|
9fac480bf83826e96f2b29cc5b18b485fe852780
|
refactor name validation to handle logical alternate cases
|
diff --git a/lib/place.rb b/lib/place.rb
index a6ef77a..16a3259 100644
--- a/lib/place.rb
+++ b/lib/place.rb
@@ -1,82 +1,88 @@
#require_relative 'pie.rb'
class Pie::Place
attr_reader :name, :description, :paths
def initialize(places, options)
@paths = {}
@places = places
extract_standard_options(options)
extract_name_and_description(options)
@places[@name] = self
end
def to_s
@name
end
def path(nodes)
nodes.each do |place_name, direction|
place = @places[place_name]
raise "#{place_name} is not a place" if place.nil?
@paths[place_name] = direction
@places[place_name].paths[name] = direction.opposite unless !direction.respond_to?(:dead_end?) || direction.dead_end?
end
end
private
def extract_name_and_description(options)
raise "You seem to have extras option in this place!" unless options.length == 1
self.name = options.keys.first
@description = options.values.first
end
def extract_standard_options(options)
end
def name=(name)
valid = false
begin
result = eval name.to_s
# if there is no exception, it's a problem like String or something Ruby knows
rescue NameError
# this is what we want, so that method_missing will be called if we use this as a place name
valid = true
rescue SyntaxError => e
- msg = "#{e.message}\nSorry, you can't name a place with a Ruby keyword, like '#{name}'"
-
- if e.message =~ /syntax error, unexpected \$end/
- msg = "#{e.message}\n"+
- "Sorry, You can't name a place 'class' "+
- "because Ruby was expecting you to define a 'class' "+
- "which is always followed by an 'end'"
+ msg = case e.message
+ when /syntax error, unexpected \$end/
+ "#{e.message}\n"+
+ "Sorry, You can't name a place 'class' "+
+ "because Ruby was expecting you to define a 'class' "+
+ "which is always followed by an 'end'"
+ when /syntax error, unexpected keyword/
+ "#{e.message}\nSorry, you can't name a place with a Ruby keyword, like '#{name}'"
+ else
+ # don't have an example where this happens, but I would guess there is one
+ "#{e.message}\nSorry, Ruby doesn't think that '#{name}' makes sense as the name of a place."
+
end
-
+
+
raise e.class, msg
rescue ArgumentError => e
msg = "#{e.message}\n"+
"You probably weren't trying to argue with Ruby, but it recognized '#{name}' and expected it to be followed by "+
"some more input, which it calls 'arguments'. Sorry '#{name}' can't be a place name."
raise e.class, msg
rescue Exception => e
# other kinds of inappropriate names
msg = "#{e.message}\nSorry, you can't name a place with something like '#{name}'"
raise e.class, msg
end
if !valid
- raise("Sorry, you can't name a place with a name that Ruby already knows like 'String'")
+ raise("Sorry, you can't name a place with a name that Ruby already knows like '#{name}'")
end
@name = name
end
end
|
blazingcloud/pie
|
3bab0ccbf8c78117f61fc6d3629ada11b2aa6f10
|
refactor place to validate name in name=
|
diff --git a/lib/place.rb b/lib/place.rb
index 29d0fc3..a6ef77a 100644
--- a/lib/place.rb
+++ b/lib/place.rb
@@ -1,81 +1,82 @@
+#require_relative 'pie.rb'
+
class Pie::Place
attr_reader :name, :description, :paths
def initialize(places, options)
@paths = {}
@places = places
-
-
extract_standard_options(options)
extract_name_and_description(options)
@places[@name] = self
end
def to_s
@name
end
def path(nodes)
nodes.each do |place_name, direction|
place = @places[place_name]
raise "#{place_name} is not a place" if place.nil?
@paths[place_name] = direction
@places[place_name].paths[name] = direction.opposite unless !direction.respond_to?(:dead_end?) || direction.dead_end?
end
end
private
-
def extract_name_and_description(options)
raise "You seem to have extras option in this place!" unless options.length == 1
- @name = options.keys.first if name_valid?(options.keys.first)
+ self.name = options.keys.first
@description = options.values.first
end
def extract_standard_options(options)
end
- def name_valid?(name)
+ def name=(name)
valid = false
begin
result = eval name.to_s
# if there is no exception, it's a problem like String or something Ruby knows
rescue NameError
# this is what we want, so that method_missing will be called if we use this as a place name
valid = true
rescue SyntaxError => e
msg = "#{e.message}\nSorry, you can't name a place with a Ruby keyword, like '#{name}'"
if e.message =~ /syntax error, unexpected \$end/
msg = "#{e.message}\n"+
"Sorry, You can't name a place 'class' "+
"because Ruby was expecting you to define a 'class' "+
"which is always followed by an 'end'"
end
raise e.class, msg
rescue ArgumentError => e
msg = "#{e.message}\n"+
"You probably weren't trying to argue with Ruby, but it recognized '#{name}' and expected it to be followed by "+
"some more input, which it calls 'arguments'. Sorry '#{name}' can't be a place name."
raise e.class, msg
rescue Exception => e
# other kinds of inappropriate names
msg = "#{e.message}\nSorry, you can't name a place with something like '#{name}'"
raise e.class, msg
end
if !valid
raise("Sorry, you can't name a place with a name that Ruby already knows like 'String'")
end
- valid
+ @name = name
end
+
+
end
diff --git a/lib/test.rb b/lib/test.rb
new file mode 100644
index 0000000..a9a258f
--- /dev/null
+++ b/lib/test.rb
@@ -0,0 +1,23 @@
+class Foo
+ attr_reader :bar
+
+ def initialize(value)
+ puts "initialize value= #{value}"
+ setup(value)
+ end
+
+ def bar=(value)
+ puts "bar= value= #{value}"
+ raise Exception, "5 not allowed" if value == 5
+ @bar = value
+ end
+
+ def setup(value)
+ puts "setup value= #{value}, #{self}"
+ self.bar=value
+ end
+private
+
+
+
+end
|
blazingcloud/pie
|
e78c3b90ee02a85b7ecccdcee8b71de75fffea9f
|
give better errors when naming places with ruby keywords, and other cases
|
diff --git a/lib/place.rb b/lib/place.rb
index 1936060..29d0fc3 100644
--- a/lib/place.rb
+++ b/lib/place.rb
@@ -1,37 +1,81 @@
class Pie::Place
attr_reader :name, :description, :paths
def initialize(places, options)
@paths = {}
@places = places
+
+
+
extract_standard_options(options)
extract_name_and_description(options)
@places[@name] = self
end
def to_s
@name
end
def path(nodes)
nodes.each do |place_name, direction|
place = @places[place_name]
raise "#{place_name} is not a place" if place.nil?
@paths[place_name] = direction
@places[place_name].paths[name] = direction.opposite unless !direction.respond_to?(:dead_end?) || direction.dead_end?
end
end
private
def extract_name_and_description(options)
raise "You seem to have extras option in this place!" unless options.length == 1
- @name = options.keys.first
+ @name = options.keys.first if name_valid?(options.keys.first)
@description = options.values.first
end
def extract_standard_options(options)
end
+
+ def name_valid?(name)
+ valid = false
+ begin
+ result = eval name.to_s
+ # if there is no exception, it's a problem like String or something Ruby knows
+
+ rescue NameError
+ # this is what we want, so that method_missing will be called if we use this as a place name
+ valid = true
+
+ rescue SyntaxError => e
+ msg = "#{e.message}\nSorry, you can't name a place with a Ruby keyword, like '#{name}'"
+
+ if e.message =~ /syntax error, unexpected \$end/
+ msg = "#{e.message}\n"+
+ "Sorry, You can't name a place 'class' "+
+ "because Ruby was expecting you to define a 'class' "+
+ "which is always followed by an 'end'"
+ end
+
+ raise e.class, msg
+
+ rescue ArgumentError => e
+ msg = "#{e.message}\n"+
+ "You probably weren't trying to argue with Ruby, but it recognized '#{name}' and expected it to be followed by "+
+ "some more input, which it calls 'arguments'. Sorry '#{name}' can't be a place name."
+ raise e.class, msg
+
+ rescue Exception => e
+ # other kinds of inappropriate names
+ msg = "#{e.message}\nSorry, you can't name a place with something like '#{name}'"
+ raise e.class, msg
+ end
+
+ if !valid
+ raise("Sorry, you can't name a place with a name that Ruby already knows like 'String'")
+ end
+
+ valid
+ end
end
diff --git a/spec/pie_spec.rb b/spec/pie_spec.rb
index 39ae7fa..cff8334 100644
--- a/spec/pie_spec.rb
+++ b/spec/pie_spec.rb
@@ -1,182 +1,227 @@
require File.join(File.expand_path(File.dirname(__FILE__)), "..", "lib", "pie")
class Game
include Pie
end
describe "baking pie" do
before do
@game = Game.new
end
describe "included in a class" do
it "can access the current_place" do
@game.instance_eval do
current_place.should == nil
place ship:"this is a ship"
current_place(:ship)
current_place.should == ship
place land:"this is land"
current_place('land')
current_place.should == land
end
end
end
describe "with template" do
it "has a default template" do
@game.template.should == :image_page
end
it "can set an alternate template" do
@game.instance_eval do
template :foo
template.should == :foo
end
end
end
describe "image declaration" do
it "can declare an image" do
@game.instance_eval do
image ship:"http://foo.com/ship.png"
images[:ship].should == "http://foo.com/ship.png"
end
end
it "can declare multiple image statements" do
@game.instance_eval do
image ship:"http://foo.com/ship.png"
image basket:"http://foo.com/basket.png"
images[:ship].should == "http://foo.com/ship.png"
images[:basket].should == "http://foo.com/basket.png"
end
end
it "can declare multiple images with one statement" do
@game.instance_eval do
image ship:"http://foo.com/ship.png",
basket:"http://foo.com/basket.png"
images[:ship].should == "http://foo.com/ship.png"
images[:basket].should == "http://foo.com/basket.png"
end
end
end
describe "creates places" do
it "raises an error when extra options are given" do
lambda {
@game.place ship:"this is a ship", extra_option:"this"
}.should raise_error
end
it "can have a description" do
@game.instance_eval do
place ship:"this is a ship"
ship.class.should == Place
ship.name.should == :ship
ship.description.should == "this is a ship"
end
end
it "doesn't contain places from other games" do
@game.instance_eval do
place ship:"this is a ship"
end
@game2 = Game.new
@game2.instance_eval do
place boat:"this is a boat"
end
puts @game.places.inspect
puts @game2.places.inspect
@game2.places.length.should == 1
end
+
+ describe "gives an appropriate error" do
+ it "when a place is named with a Ruby keyword, like 'end'" do
+ lambda {
+ @game.instance_eval do
+ place end:"This is where it all ends."
+ end
+ }.should raise_error(SyntaxError, "(eval):1: syntax error, unexpected keyword_end\nSorry, you can't name a place with a Ruby keyword, like 'end'")
+ end
+
+ it "when a place is named with a Ruby keyword, like 'do'" do
+ lambda {
+ @game.instance_eval do
+ place do:"Don't step in this."
+ end
+ }.should raise_error(SyntaxError, "(eval):1: syntax error, unexpected keyword_do_block\nSorry, you can't name a place with a Ruby keyword, like 'do'")
+ end
+
+ it "when a place is named with a Ruby keyword, like 'class'" do
+ lambda {
+ @game.instance_eval do
+ place class:"This is a place in school."
+ end
+ }.should raise_error(SyntaxError, "(eval):1: syntax error, unexpected $end\nclass\n ^\n"+
+ "Sorry, You can't name a place 'class' because Ruby was expecting you to define a 'class' which is always followed by an 'end'")
+ end
+
+ it "when a place is named with a Ruby method, like 'eval'" do
+ lambda {
+ @game.instance_eval do
+ place eval:"Now you're playing with fire."
+ end
+ }.should raise_error(ArgumentError, "wrong number of arguments (0 for 1..4)\n" +
+ "You probably weren't trying to argue with Ruby, but it recognized 'eval' and expected it to be followed by "+
+ "some more input, which it calls 'arguments'. Sorry 'eval' can't be a place name.")
+ end
+
+ it "when a place is named with a built-in class" do
+ lambda {
+ @game.instance_eval do
+ place String:"This is a really long place made of yarn."
+ end
+ }.should raise_error(Exception, "Sorry, you can't name a place with a name that Ruby already knows like 'String'")
+ end
+ end
describe "with paths" do
before do
@game.instance_eval do
place field:"You are in a large, grassy field. You see many trees to the north and a path to the east"
place forest:"It is dark in the forest"
place cliff_top:"The path ends at the top of a steep cliff"
place cliff_bottom:"You walked off the cliff and fell to your death"
end
end
it "should have links between two places" do
@game.instance_eval do
field.path forest:north
field.paths.should == {forest:north}
forest.paths.should == {field:south}
end
end
it "should have one way links" do
@game.instance_eval do
cliff_top.path cliff_bottom:east!
cliff_top.paths.should == {cliff_bottom:east}
cliff_bottom.paths.should == {}
end
end
it "should support simple strings" do
@game.instance_eval do
field.path cliff_bottom:"flying leap"
field.paths[:cliff_bottom].should == "flying leap"
end
end
it "raises an error when place doesn't exist" do
lambda {
@game.instance_eval do
- field.path :xxx => north
+ field.path xxx:north
end
}.should raise_error(Exception, "xxx is not a place")
end
end
end
# describe "can access places" do
# before do
# ship description:"ookina fune"
# building description:"ookina biru"
# tower description:"ookina towa"
# end
#
# it "which are accessible by named key (symbol)" do
# ship = $pie.places[:ship]
# ship.should_not be_nil
# ship[:description].should == "ookina fune"
# end
#
# it "which are accessible by named key (string)" do
# ship = $pie.places["ship"]
# ship.should_not be_nil
# ship[:description].should == "ookina fune"
# end
#
# it "resulting in 2 places" do
# $pie.places.length.should == 3
# end
#
# it "and can find place after named place" do
# building = $pie.places.after(:ship)
# building.should_not be_nil
# building[:description].should == "ookina biru"
# end
#
# it "and finds nil after last place" do
# nothing = $pie.places.after(:tower)
# nothing.should be_nil
# end
#
# it "and can find place before named place" do
# building = $pie.places.before(:tower)
# building.should_not be_nil
# building[:description].should == "ookina biru"
# end
#
# it "and finds nil before first place" do
# nothing = $pie.places.before(:ship)
# nothing.should be_nil
# end
# end
end
|
blazingcloud/pie
|
59357fdbd5b793747cfbbed513e6d232fe8c685b
|
report error when place name isn't recognized as a path arg
|
diff --git a/lib/place.rb b/lib/place.rb
index 1bab2c1..1936060 100644
--- a/lib/place.rb
+++ b/lib/place.rb
@@ -1,34 +1,37 @@
class Pie::Place
attr_reader :name, :description, :paths
def initialize(places, options)
@paths = {}
@places = places
extract_standard_options(options)
extract_name_and_description(options)
@places[@name] = self
end
def to_s
@name
end
def path(nodes)
nodes.each do |place_name, direction|
- paths[place_name] = direction
+ place = @places[place_name]
+ raise "#{place_name} is not a place" if place.nil?
+
+ @paths[place_name] = direction
@places[place_name].paths[name] = direction.opposite unless !direction.respond_to?(:dead_end?) || direction.dead_end?
end
end
private
def extract_name_and_description(options)
raise "You seem to have extras option in this place!" unless options.length == 1
@name = options.keys.first
@description = options.values.first
end
def extract_standard_options(options)
end
end
diff --git a/pie.gemspec b/pie.gemspec
index 015c4af..d8d5d09 100644
--- a/pie.gemspec
+++ b/pie.gemspec
@@ -1,11 +1,11 @@
spec = Gem::Specification.new do |s|
s.name = 'pie'
s.authors = 'Sarah Allen, Sarah Mei, Rich Kilmer'
s.homepage = 'http://github.com/blazingcloud/pie'
- s.version = '0.2.9'
+ s.version = '0.2.11'
s.summary = 'Pie, a language for developing games and books'
s.files = Dir['lib/*.rb']+Dir['views/*.erb']+['README.md', 'MIT-LICENSE.txt', 'bin/pie']
s.bindir = 'bin'
s.executables << 'pie'
end
diff --git a/spec/pie_spec.rb b/spec/pie_spec.rb
index c287a1b..39ae7fa 100644
--- a/spec/pie_spec.rb
+++ b/spec/pie_spec.rb
@@ -1,175 +1,182 @@
require File.join(File.expand_path(File.dirname(__FILE__)), "..", "lib", "pie")
class Game
include Pie
end
describe "baking pie" do
before do
@game = Game.new
end
describe "included in a class" do
it "can access the current_place" do
@game.instance_eval do
current_place.should == nil
place ship:"this is a ship"
current_place(:ship)
current_place.should == ship
place land:"this is land"
current_place('land')
current_place.should == land
end
end
end
describe "with template" do
it "has a default template" do
@game.template.should == :image_page
end
it "can set an alternate template" do
@game.instance_eval do
template :foo
template.should == :foo
end
end
end
describe "image declaration" do
it "can declare an image" do
@game.instance_eval do
image ship:"http://foo.com/ship.png"
images[:ship].should == "http://foo.com/ship.png"
end
end
it "can declare multiple image statements" do
@game.instance_eval do
image ship:"http://foo.com/ship.png"
image basket:"http://foo.com/basket.png"
images[:ship].should == "http://foo.com/ship.png"
images[:basket].should == "http://foo.com/basket.png"
end
end
it "can declare multiple images with one statement" do
@game.instance_eval do
image ship:"http://foo.com/ship.png",
basket:"http://foo.com/basket.png"
images[:ship].should == "http://foo.com/ship.png"
images[:basket].should == "http://foo.com/basket.png"
end
end
end
describe "creates places" do
- it "can create a place with extra options raises an error" do
+ it "raises an error when extra options are given" do
lambda {
@game.place ship:"this is a ship", extra_option:"this"
}.should raise_error
end
- it "can create a place with a description" do
+ it "can have a description" do
@game.instance_eval do
place ship:"this is a ship"
ship.class.should == Place
ship.name.should == :ship
ship.description.should == "this is a ship"
end
end
it "doesn't contain places from other games" do
@game.instance_eval do
place ship:"this is a ship"
end
@game2 = Game.new
@game2.instance_eval do
place boat:"this is a boat"
end
puts @game.places.inspect
puts @game2.places.inspect
@game2.places.length.should == 1
-
end
describe "with paths" do
before do
@game.instance_eval do
place field:"You are in a large, grassy field. You see many trees to the north and a path to the east"
place forest:"It is dark in the forest"
place cliff_top:"The path ends at the top of a steep cliff"
place cliff_bottom:"You walked off the cliff and fell to your death"
end
end
it "should have links between two places" do
@game.instance_eval do
field.path forest:north
field.paths.should == {forest:north}
forest.paths.should == {field:south}
end
end
it "should have one way links" do
@game.instance_eval do
cliff_top.path cliff_bottom:east!
cliff_top.paths.should == {cliff_bottom:east}
cliff_bottom.paths.should == {}
end
end
it "should support simple strings" do
@game.instance_eval do
field.path cliff_bottom:"flying leap"
field.paths[:cliff_bottom].should == "flying leap"
end
end
+
+ it "raises an error when place doesn't exist" do
+ lambda {
+ @game.instance_eval do
+ field.path :xxx => north
+ end
+ }.should raise_error(Exception, "xxx is not a place")
+ end
end
end
# describe "can access places" do
# before do
# ship description:"ookina fune"
# building description:"ookina biru"
# tower description:"ookina towa"
# end
#
# it "which are accessible by named key (symbol)" do
# ship = $pie.places[:ship]
# ship.should_not be_nil
# ship[:description].should == "ookina fune"
# end
#
# it "which are accessible by named key (string)" do
# ship = $pie.places["ship"]
# ship.should_not be_nil
# ship[:description].should == "ookina fune"
# end
#
# it "resulting in 2 places" do
# $pie.places.length.should == 3
# end
#
# it "and can find place after named place" do
# building = $pie.places.after(:ship)
# building.should_not be_nil
# building[:description].should == "ookina biru"
# end
#
# it "and finds nil after last place" do
# nothing = $pie.places.after(:tower)
# nothing.should be_nil
# end
#
# it "and can find place before named place" do
# building = $pie.places.before(:tower)
# building.should_not be_nil
# building[:description].should == "ookina biru"
# end
#
# it "and finds nil before first place" do
# nothing = $pie.places.before(:ship)
# nothing.should be_nil
# end
# end
end
|
blazingcloud/pie
|
bbbcee0bce4ae6a3e81d683d3a8f51816c1c0343
|
games should not include places from other games
|
diff --git a/.bundle/config b/.bundle/config
index 8ebbe30..2fbf0ff 100644
--- a/.bundle/config
+++ b/.bundle/config
@@ -1,2 +1 @@
----
-BUNDLE_DISABLE_SHARED_GEMS: "1"
+--- {}
diff --git a/lib/pie.rb b/lib/pie.rb
index ede413d..69fbd6b 100644
--- a/lib/pie.rb
+++ b/lib/pie.rb
@@ -1,93 +1,86 @@
module Pie
-
+ attr_accessor :places
+
+ def initialize
+ @places = {}
+ end
def self.[](key)
(@map ||= {})[key]
end
def self.[]=(key, value)
(@map ||= {})[key] = value
end
def self.language=(language)
@language = language
end
def self.localized(id)
@values ||= {
:japanese => {
:go_north => "Go North (in jp!)",
:go_south => "Go South (in jp!)",
:go_east => "Go East (in jp!)",
:go_west => "Go West (in jp!)"
},
:english => {
:go_north => "Go North",
:go_south => "Go South",
:go_east => "Go East",
:go_west => "Go West"
}
}
@values[@language || :english][id]
end
def self.places
Pie[:places] ||= {}
end
def template(name = nil)
if name
Pie[:template] = name.to_sym
else
Pie[:template] || :image_page
end
end
def images
Pie[:images] ||= {}
end
def image(image_maps)
images.merge!(image_maps)
end
def place(options)
- new_place = Place.new(options)
- name = new_place.name
- #self.instance_eval %{
- # def #{name}
- # places[:#{name}]
- # end
- #}
- places[new_place.name] = new_place
+ Place.new(places, options)
end
def method_missing name
place = places[name.to_sym]
raise NoMethodError if place.nil?
place
end
def current_place(name=nil)
if name
Pie[:current_place] = places[name.to_sym]
else
Pie[:current_place]
end
end
def current_image
images[current_place.name] if current_place
end
-
- def places
- Pie.places
- end
-
+
def language(language)
Pie.language = language
end
end
require 'place'
require 'direction'
diff --git a/lib/place.rb b/lib/place.rb
index 1546609..1bab2c1 100644
--- a/lib/place.rb
+++ b/lib/place.rb
@@ -1,32 +1,34 @@
class Pie::Place
attr_reader :name, :description, :paths
- def initialize(options)
+ def initialize(places, options)
@paths = {}
+ @places = places
extract_standard_options(options)
extract_name_and_description(options)
+ @places[@name] = self
end
def to_s
@name
end
def path(nodes)
nodes.each do |place_name, direction|
paths[place_name] = direction
- Pie.places[place_name].paths[name] = direction.opposite unless !direction.respond_to?(:dead_end?) || direction.dead_end?
+ @places[place_name].paths[name] = direction.opposite unless !direction.respond_to?(:dead_end?) || direction.dead_end?
end
end
private
def extract_name_and_description(options)
raise "You seem to have extras option in this place!" unless options.length == 1
@name = options.keys.first
@description = options.values.first
end
def extract_standard_options(options)
end
end
diff --git a/spec/pie_spec.rb b/spec/pie_spec.rb
index 13ffd32..c287a1b 100644
--- a/spec/pie_spec.rb
+++ b/spec/pie_spec.rb
@@ -1,159 +1,175 @@
require File.join(File.expand_path(File.dirname(__FILE__)), "..", "lib", "pie")
class Game
include Pie
end
describe "baking pie" do
before do
@game = Game.new
end
describe "included in a class" do
it "can access the current_place" do
@game.instance_eval do
current_place.should == nil
place ship:"this is a ship"
current_place(:ship)
current_place.should == ship
place land:"this is land"
current_place('land')
current_place.should == land
end
end
end
describe "with template" do
it "has a default template" do
@game.template.should == :image_page
end
it "can set an alternate template" do
@game.instance_eval do
template :foo
template.should == :foo
end
end
end
describe "image declaration" do
it "can declare an image" do
@game.instance_eval do
image ship:"http://foo.com/ship.png"
images[:ship].should == "http://foo.com/ship.png"
end
end
it "can declare multiple image statements" do
@game.instance_eval do
image ship:"http://foo.com/ship.png"
image basket:"http://foo.com/basket.png"
images[:ship].should == "http://foo.com/ship.png"
images[:basket].should == "http://foo.com/basket.png"
end
end
it "can declare multiple images with one statement" do
@game.instance_eval do
image ship:"http://foo.com/ship.png",
basket:"http://foo.com/basket.png"
images[:ship].should == "http://foo.com/ship.png"
images[:basket].should == "http://foo.com/basket.png"
end
end
end
describe "creates places" do
it "can create a place with extra options raises an error" do
lambda {
@game.place ship:"this is a ship", extra_option:"this"
}.should raise_error
end
it "can create a place with a description" do
@game.instance_eval do
place ship:"this is a ship"
ship.class.should == Place
ship.name.should == :ship
ship.description.should == "this is a ship"
end
end
+ it "doesn't contain places from other games" do
+ @game.instance_eval do
+ place ship:"this is a ship"
+ end
+
+ @game2 = Game.new
+ @game2.instance_eval do
+ place boat:"this is a boat"
+ end
+
+ puts @game.places.inspect
+ puts @game2.places.inspect
+ @game2.places.length.should == 1
+
+ end
+
describe "with paths" do
before do
@game.instance_eval do
place field:"You are in a large, grassy field. You see many trees to the north and a path to the east"
place forest:"It is dark in the forest"
place cliff_top:"The path ends at the top of a steep cliff"
place cliff_bottom:"You walked off the cliff and fell to your death"
end
end
it "should have links between two places" do
@game.instance_eval do
field.path forest:north
field.paths.should == {forest:north}
forest.paths.should == {field:south}
end
end
it "should have one way links" do
@game.instance_eval do
cliff_top.path cliff_bottom:east!
cliff_top.paths.should == {cliff_bottom:east}
cliff_bottom.paths.should == {}
end
end
it "should support simple strings" do
@game.instance_eval do
field.path cliff_bottom:"flying leap"
field.paths[:cliff_bottom].should == "flying leap"
end
end
end
end
# describe "can access places" do
# before do
# ship description:"ookina fune"
# building description:"ookina biru"
# tower description:"ookina towa"
# end
#
# it "which are accessible by named key (symbol)" do
# ship = $pie.places[:ship]
# ship.should_not be_nil
# ship[:description].should == "ookina fune"
# end
#
# it "which are accessible by named key (string)" do
# ship = $pie.places["ship"]
# ship.should_not be_nil
# ship[:description].should == "ookina fune"
# end
#
# it "resulting in 2 places" do
# $pie.places.length.should == 3
# end
#
# it "and can find place after named place" do
# building = $pie.places.after(:ship)
# building.should_not be_nil
# building[:description].should == "ookina biru"
# end
#
# it "and finds nil after last place" do
# nothing = $pie.places.after(:tower)
# nothing.should be_nil
# end
#
# it "and can find place before named place" do
# building = $pie.places.before(:tower)
# building.should_not be_nil
# building[:description].should == "ookina biru"
# end
#
# it "and finds nil before first place" do
# nothing = $pie.places.before(:ship)
# nothing.should be_nil
# end
# end
end
|
blazingcloud/pie
|
c6d51376847e592887dd1643ef87506e06dc910a
|
added Matthew Bass as a contributor to the README, updated gem
|
diff --git a/README.md b/README.md
index a9c60dc..5b4b0d7 100644
--- a/README.md
+++ b/README.md
@@ -1,52 +1,53 @@
# Pie
A game development DSL, inspired by Yasuko Ohba's Ruby Kaigi talk and a late night conversation with @knowtheory, @wycats, @sarahmei and @ultrasaurus.
Pie requires Ruby 1.9, because it is so cool.
## Examples
### Game
pie game.pie
then go to:
http://localhost:31415/park
Follow links to wander around the game world. Yes, that is all there is right now.
### Book -- NOT WORKING YET
There is a sample in book.rb. To use it:
pie book.pie
then go to:
http://localhost:31415/ship
http://localhost:31415/building
http://localhost:31415/tower
Someday there will be UI to change pages.
## Issues?
Bugs and features are tracked here: http://www.pivotaltracker.com/projects/115060
I want to try to resist adding any new features until we have no bugs and kid-friendly error messages. Help is welcome. Feel free to fork and submit pull requests or just tweet or email ideas.
## Pie Contributors
Core team (in order of appearance)
-* Sarah Allen
-* Sarah Mei
-* Rich Kilmer
+* Sarah Allen @ultrasaurs
+* Sarah Mei @sarahmei
+* Rich Kilmer @richkilmer
Contributors
+* Matthew Bass @pelargir
* Dan Steinicke
* Akira Matsuda
* Chad Fowler
diff --git a/pie.gemspec b/pie.gemspec
index 7ad6a3f..015c4af 100644
--- a/pie.gemspec
+++ b/pie.gemspec
@@ -1,11 +1,11 @@
spec = Gem::Specification.new do |s|
s.name = 'pie'
s.authors = 'Sarah Allen, Sarah Mei, Rich Kilmer'
s.homepage = 'http://github.com/blazingcloud/pie'
- s.version = '0.2.8'
+ s.version = '0.2.9'
s.summary = 'Pie, a language for developing games and books'
s.files = Dir['lib/*.rb']+Dir['views/*.erb']+['README.md', 'MIT-LICENSE.txt', 'bin/pie']
s.bindir = 'bin'
s.executables << 'pie'
end
|
blazingcloud/pie
|
52264d418abd64f158187e3e9aa38e6aa200e879
|
visiting root url uses first place in list
|
diff --git a/.gitignore b/.gitignore
index 11401d9..c6cdda9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,4 @@
.idea
+.rvmrc
*~
*.gem
diff --git a/Rakefile b/Rakefile
new file mode 100644
index 0000000..3d4824d
--- /dev/null
+++ b/Rakefile
@@ -0,0 +1,8 @@
+require 'rake'
+require 'spec/version'
+require 'spec/rake/spectask'
+require 'spec/ruby'
+
+Spec::Rake::SpecTask.new
+
+task :default => :spec
diff --git a/lib/pie_server.rb b/lib/pie_server.rb
index 9ea6afd..6800e52 100644
--- a/lib/pie_server.rb
+++ b/lib/pie_server.rb
@@ -1,30 +1,26 @@
require 'sinatra/base'
class Pie::WebApp < Sinatra::Base
set :root, File.join(File.expand_path(File.dirname(__FILE__)), "..")
- get '/' do
- "hello"
- end
-
- get '/:place_name' do
+ get '/*' do
puts "env= #{request.env.inspect}"
puts "request.env[PIE_DATA]= #{request.env["PIE_DATA"].inspect}"
- pie ||= request.env["PIE_DATA"]
- pie ||= settings.pie_data if settings.respond_to? :pie_data
+ pie ||= request.env["PIE_DATA"] || settings.pie_data
puts "pie = #{pie.inspect}"
if pie
- name = params[:place_name].to_sym
+ splat = params[:splat].find { |e| e.length > 0 }
+ name = (splat || settings.pie_data.places.first.first).to_sym
pie.current_place(name) unless name.nil?
puts "current place name is #{pie.current_place.name}"
puts "current place is #{pie.current_place.description}"
puts "--- skip out"; return if pie.current_place.nil?
puts "current links are #{pie.current_place.paths.inspect}"
puts "displaying template: #{pie.template.inspect}"
erb pie.template, {}, {:pie => pie}
else
puts "NO PIE! AAAAAH!"
end
end
end
diff --git a/spec/pie_app_spec.rb b/spec/pie_app_spec.rb
index d4c09cc..be97ff3 100644
--- a/spec/pie_app_spec.rb
+++ b/spec/pie_app_spec.rb
@@ -1,43 +1,48 @@
$LOAD_PATH << File.join(File.expand_path(File.dirname(__FILE__)), "..", "lib")
require 'pie'
require 'pie_server'
require 'capybara'
require 'capybara/dsl'
describe "app created with pie" do
include Capybara
include Pie
before do
Capybara.app = Pie::WebApp
end
- it "should say hello for the root path" do
- visit '/'
- page.should have_content "hello"
+ describe "root path" do
+ before do
+ place ship:"ookina fune"
+ end
+ it "should visit the first place in the list" do
+ visit '/'
+ page.should have_content('ookina fune')
+ end
end
describe "with one place and an image" do
before do
place ship:"ookina fune"
image ship:"images/big_ship.jpg"
end
it "should display the ship page" do
visit '/ship'
page.should have_content('ookina fune')
end
end
describe "with two places and images" do
before do
place ship:"ookina fune"
place building:"ookina biru"
image ship:"images/big_ship.jpg"
image building:"images/building.jpg"
end
it "should display the next button" do
visit '/ship'
page.should have_content('next')
end
end
end
|
blazingcloud/pie
|
5dd4a3572e158f03788ebccea8ec7de19ef4f187
|
change instance eval to method_missing so it works in rhodes
|
diff --git a/lib/pie.rb b/lib/pie.rb
index 6c14897..ede413d 100644
--- a/lib/pie.rb
+++ b/lib/pie.rb
@@ -1,87 +1,93 @@
module Pie
def self.[](key)
(@map ||= {})[key]
end
def self.[]=(key, value)
(@map ||= {})[key] = value
end
def self.language=(language)
@language = language
end
def self.localized(id)
@values ||= {
:japanese => {
:go_north => "Go North (in jp!)",
:go_south => "Go South (in jp!)",
:go_east => "Go East (in jp!)",
:go_west => "Go West (in jp!)"
},
:english => {
:go_north => "Go North",
:go_south => "Go South",
:go_east => "Go East",
:go_west => "Go West"
}
}
@values[@language || :english][id]
end
def self.places
Pie[:places] ||= {}
end
def template(name = nil)
if name
Pie[:template] = name.to_sym
else
Pie[:template] || :image_page
end
end
def images
Pie[:images] ||= {}
end
def image(image_maps)
images.merge!(image_maps)
end
def place(options)
new_place = Place.new(options)
name = new_place.name
- self.instance_eval %{
- def #{name}
- places[:#{name}]
- end
- }
+ #self.instance_eval %{
+ # def #{name}
+ # places[:#{name}]
+ # end
+ #}
places[new_place.name] = new_place
end
+
+ def method_missing name
+ place = places[name.to_sym]
+ raise NoMethodError if place.nil?
+ place
+ end
def current_place(name=nil)
if name
Pie[:current_place] = places[name.to_sym]
else
Pie[:current_place]
end
end
def current_image
images[current_place.name] if current_place
end
def places
Pie.places
end
def language(language)
Pie.language = language
end
end
require 'place'
require 'direction'
diff --git a/syntax_ideas.rb b/syntax_ideas.rb
new file mode 100644
index 0000000..24170ae
--- /dev/null
+++ b/syntax_ideas.rb
@@ -0,0 +1,106 @@
+# Draft 1
+
+create_places do
+ cave description:"You are in a big cave", connects_to: { forest:"Go out"}
+ forest description:"The forest is very dark", connects_to: { cave:"North", cliff:"East"}
+ cliff description:"There is a sheer cliff that is too steep to climb", connects_to: { forest:"East"}
+end
+
+create_player do
+ evolve [egg:forest, rabbit:cave, smurf, wizard, warrior]
+end
+
+images {
+ cave:"http://flickr.com/trees.jpg",
+ forest:"http://flickr.com/forest.jpg",
+ cliff:"http://flickr.com/something.jpg",
+ egg:"http://flickr.com/egg.jpg",
+ rabbit:"http://ultrasaurus.com/photos/rabbit.png"
+ ...
+}
+
+start forest
+
+
+# Draft 2 -- implicit next/prev, images with nicer syntax (or maybe not)
+
+create_places do
+ ship description:"ookina funa"
+ building description:"ookina biru"
+ tower description:"ookina towa"
+end
+
+image ship:"http://flickr.com/trees.jpg",
+ building:"http://flickr.com/forest.jpg",
+ tower:"http://flickr.com/something.jpg",
+
+sounds {
+ ship:"ookina-foona.wav",
+ building:"biru.wav",
+ tower:"towa.wav"
+}
+
+# First implementation
+
+make_pie do
+ create_places do
+ ship description:"大ããªè¹"
+ building description:"ookina biru"
+ tower description:"ookina towa"
+ end
+
+ image ship:"images/big_ship.jpg",
+ building:"images/building.jpg",
+ tower:"images/tokyo_tower.jpg"
+end
+
+make_pie do
+ template :game_screen
+
+ create_places do
+ park description:"You are in a park. You see trees to the north and a path to the east", links:{trees:"North", river_edge:"East"}
+ trees description:"You are in a Japanese garden.", links:{park:"South"}
+ river_edge description:"The path ends at a river", links:{in_the_river:"East", park:"West"}
+ in_the_river description:"You walk into the river and down"
+ end
+
+ image park:"images/park.JPG"
+ image river_edge:"images/water.JPG"
+ image trees:"images/trees.JPG"
+end
+
+# Need to write code to report nicer errors
+# method_missing makes for weird errors
+
+ it "cannot create a place if options are invalid (given as a symbol not a Hash)" do
+ make_pie do
+ create_places do
+ result = ship :invalid
+ result.should == nil
+ end
+ end
+ $pie.places[:ship].should == nil
+ end
+
+ def method_missing name, options = {}
+ unless options.is_a? Hash
+ puts "options for creating a place must have key and value"
+ return
+ end
+
+# Issues:
+* image syntax is sensitive to space and this won't work:
+ image park :"images/park.JPG"
+* creating two-way connections, which are common is cumbersome
+* want to keep game logic in one place and as concise as possible
+
+Solution:
+
+map do
+ path {cave:"go into the forest", forest:"enter tunnel"}
+ path {cave:"step into hole", hole:no_way_back}
+end
+
+
+
+
|
blazingcloud/pie
|
eae43036b56d952ce9c43db64d3d9265f81460de
|
fixup pie_server for setting data
|
diff --git a/lib/pie_server.rb b/lib/pie_server.rb
index 5315f7b..9ea6afd 100644
--- a/lib/pie_server.rb
+++ b/lib/pie_server.rb
@@ -1,26 +1,30 @@
require 'sinatra/base'
class Pie::WebApp < Sinatra::Base
set :root, File.join(File.expand_path(File.dirname(__FILE__)), "..")
get '/' do
"hello"
end
get '/:place_name' do
- puts "settings.pie_data = #{settings.pie_data.inspect}"
-
- pie ||= settings.pie_data
+ puts "env= #{request.env.inspect}"
+ puts "request.env[PIE_DATA]= #{request.env["PIE_DATA"].inspect}"
pie ||= request.env["PIE_DATA"]
+ pie ||= settings.pie_data if settings.respond_to? :pie_data
puts "pie = #{pie.inspect}"
+ if pie
name = params[:place_name].to_sym
pie.current_place(name) unless name.nil?
puts "current place name is #{pie.current_place.name}"
puts "current place is #{pie.current_place.description}"
puts "--- skip out"; return if pie.current_place.nil?
puts "current links are #{pie.current_place.paths.inspect}"
puts "displaying template: #{pie.template.inspect}"
erb pie.template, {}, {:pie => pie}
+ else
+ puts "NO PIE! AAAAAH!"
+ end
end
end
diff --git a/pie.gemspec b/pie.gemspec
index a79b6da..7ad6a3f 100644
--- a/pie.gemspec
+++ b/pie.gemspec
@@ -1,11 +1,11 @@
spec = Gem::Specification.new do |s|
s.name = 'pie'
s.authors = 'Sarah Allen, Sarah Mei, Rich Kilmer'
s.homepage = 'http://github.com/blazingcloud/pie'
- s.version = '0.2.7'
+ s.version = '0.2.8'
s.summary = 'Pie, a language for developing games and books'
s.files = Dir['lib/*.rb']+Dir['views/*.erb']+['README.md', 'MIT-LICENSE.txt', 'bin/pie']
s.bindir = 'bin'
s.executables << 'pie'
end
|
blazingcloud/pie
|
273fbcdf45ce5824c472f5831237a0658170c166
|
namespec WebApp inside Pie module
|
diff --git a/bin/pie b/bin/pie
index b42a809..444dfcb 100755
--- a/bin/pie
+++ b/bin/pie
@@ -1,40 +1,40 @@
#!/usr/bin/env ruby
if RUBY_VERSION < "1.9.0"
puts "Error: pie requires Ruby 1.9, please use RVM."
exit
end
if ARGV.size == 0
puts "Usage: pie myfile"
exit
end
pie_file = ARGV.first
pie_file = "#{pie_file}.pie" unless File.exist?(pie_file)
unless File.exist?(pie_file)
puts "Unknown file #{ARGV.first}, please try again."
exit
end
begin
require 'pie'
rescue LoadError
$LOAD_PATH.unshift File.expand_path(File.join(File.dirname(__FILE__), "..", "lib"))
require 'pie'
end
class PieEnvironment
include Pie
end
pie_data = PieEnvironment.new
File.open(pie_file) do |f|
pie_data.instance_eval do
eval(f.read)
end
end
require 'pie_server'
-WebApp.set :pie_data, pie_data
-WebApp.run! :port => 31415
+Pie::WebApp.set :pie_data, pie_data
+Pie::WebApp.run! :port => 31415
diff --git a/lib/pie_server.rb b/lib/pie_server.rb
index 91065ea..5315f7b 100644
--- a/lib/pie_server.rb
+++ b/lib/pie_server.rb
@@ -1,27 +1,26 @@
require 'sinatra/base'
-class WebApp < Sinatra::Base
+class Pie::WebApp < Sinatra::Base
set :root, File.join(File.expand_path(File.dirname(__FILE__)), "..")
get '/' do
"hello"
end
get '/:place_name' do
- puts "============================================"
puts "settings.pie_data = #{settings.pie_data.inspect}"
pie ||= settings.pie_data
pie ||= request.env["PIE_DATA"]
puts "pie = #{pie.inspect}"
name = params[:place_name].to_sym
pie.current_place(name) unless name.nil?
puts "current place name is #{pie.current_place.name}"
puts "current place is #{pie.current_place.description}"
puts "--- skip out"; return if pie.current_place.nil?
puts "current links are #{pie.current_place.paths.inspect}"
puts "displaying template: #{pie.template.inspect}"
erb pie.template, {}, {:pie => pie}
end
end
diff --git a/spec/pie_app_spec.rb b/spec/pie_app_spec.rb
index 7a85481..d4c09cc 100644
--- a/spec/pie_app_spec.rb
+++ b/spec/pie_app_spec.rb
@@ -1,43 +1,43 @@
$LOAD_PATH << File.join(File.expand_path(File.dirname(__FILE__)), "..", "lib")
require 'pie'
require 'pie_server'
require 'capybara'
require 'capybara/dsl'
describe "app created with pie" do
include Capybara
include Pie
before do
- Capybara.app = WebApp
+ Capybara.app = Pie::WebApp
end
it "should say hello for the root path" do
visit '/'
page.should have_content "hello"
end
describe "with one place and an image" do
before do
place ship:"ookina fune"
image ship:"images/big_ship.jpg"
end
it "should display the ship page" do
visit '/ship'
page.should have_content('ookina fune')
end
end
describe "with two places and images" do
before do
place ship:"ookina fune"
place building:"ookina biru"
image ship:"images/big_ship.jpg"
image building:"images/building.jpg"
end
it "should display the next button" do
visit '/ship'
page.should have_content('next')
end
end
end
|
blazingcloud/pie
|
f57a687f2c760817b49c539ec017f96c7c958b04
|
use Sinatra settings instead of global var -- whew
|
diff --git a/bin/pie b/bin/pie
index cba0b4b..b42a809 100755
--- a/bin/pie
+++ b/bin/pie
@@ -1,38 +1,40 @@
#!/usr/bin/env ruby
if RUBY_VERSION < "1.9.0"
puts "Error: pie requires Ruby 1.9, please use RVM."
exit
end
if ARGV.size == 0
puts "Usage: pie myfile"
exit
end
pie_file = ARGV.first
pie_file = "#{pie_file}.pie" unless File.exist?(pie_file)
unless File.exist?(pie_file)
puts "Unknown file #{ARGV.first}, please try again."
exit
end
begin
require 'pie'
rescue LoadError
$LOAD_PATH.unshift File.expand_path(File.join(File.dirname(__FILE__), "..", "lib"))
require 'pie'
end
-class PieThing
-include Pie
+class PieEnvironment
+ include Pie
end
-$thing = PieThing.new
+pie_data = PieEnvironment.new
File.open(pie_file) do |f|
-$thing.instance_eval do
+pie_data.instance_eval do
eval(f.read)
end
end
require 'pie_server'
+
+WebApp.set :pie_data, pie_data
WebApp.run! :port => 31415
diff --git a/lib/pie_server.rb b/lib/pie_server.rb
index d57a83f..91065ea 100644
--- a/lib/pie_server.rb
+++ b/lib/pie_server.rb
@@ -1,25 +1,27 @@
require 'sinatra/base'
class WebApp < Sinatra::Base
set :root, File.join(File.expand_path(File.dirname(__FILE__)), "..")
get '/' do
"hello"
end
get '/:place_name' do
puts "============================================"
- thing ||= $thing
- thing ||= request.env["PIE_THING"]
- puts "thing = #{thing.inspect}"
+ puts "settings.pie_data = #{settings.pie_data.inspect}"
+
+ pie ||= settings.pie_data
+ pie ||= request.env["PIE_DATA"]
+ puts "pie = #{pie.inspect}"
name = params[:place_name].to_sym
- thing.current_place(name) unless name.nil?
- puts "current place name is #{thing.current_place.name}"
- puts "current place is #{thing.current_place.description}"
- puts "--- skip out"; return if thing.current_place.nil?
- puts "current links are #{thing.current_place.paths.inspect}"
- puts "displaying template: #{thing.template.inspect}"
- erb thing.template, {}, {:thing => thing}
+ pie.current_place(name) unless name.nil?
+ puts "current place name is #{pie.current_place.name}"
+ puts "current place is #{pie.current_place.description}"
+ puts "--- skip out"; return if pie.current_place.nil?
+ puts "current links are #{pie.current_place.paths.inspect}"
+ puts "displaying template: #{pie.template.inspect}"
+ erb pie.template, {}, {:pie => pie}
end
end
diff --git a/views/full_screen.erb b/views/full_screen.erb
index e38d3f0..5628b2e 100644
--- a/views/full_screen.erb
+++ b/views/full_screen.erb
@@ -1,63 +1,63 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title><%= current_place.name %></title>
<style type="text/css" media="screen">
img.bg {
/* Set rules to fill background */
min-height: 100%;
min-width: 1024px;
/* Set up proportionate scaling */
width: 100%;
height: auto;
/* Set up positioning */
position: fixed;
top: 0;
left: 0;
}
@media screen and (max-width: 1024px){
img.bg {
left: 50%;
margin-left: -512px; }
}
div#content {
/* This is the only important rule */
/* We need our content to show up on top of the background */
position: relative;
/* These have no effect on the functionality */
width: 80%;
margin: 0 auto;
background: #fff;
padding: 20px;
font-family: helvetica, arial, sans-serif;
font-size: 12pt;
line-height: 14pt;
-moz-box-shadow: #000 4px 4px 10px;
-webkit-box-shadow: #000 4px 4px 10px;
}
</style>
</head>
<body>
-<img src="<%= current_image %>" class="bg" />
+<img src="<%= pie.current_image %>" class="bg" />
<div id="content">
- <p><%= current_place.description %></p>
+ <p><%= pie.current_place.description %></p>
<p>
- <% current_place.paths.each do |place_name, label| %>
+ <% pie.current_place.paths.each do |place_name, label| %>
<%= " <a href='#{place_name}'>#{label}</a> " %>
<% end %>
</p>
</div>
</body>
</html>
diff --git a/views/game_screen.erb b/views/game_screen.erb
index 4537f6f..9369f7a 100644
--- a/views/game_screen.erb
+++ b/views/game_screen.erb
@@ -1,69 +1,69 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title><%= $current %></title>
<style type="text/css" media="screen">
body {
background: #000;
}
div#background {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%
}
div#background img {
/* Set up proportionate scaling */
width: auto;
height: 100%;
/* Set up positioning */
margin-left: auto;
margin-right: auto;
display: block;
}
div#content {
/* This is the only important rule */
/* We need our content to show up on top of the background */
position: relative;
/* These have no effect on the functionality */
width: 400px;
margin: 0 auto;
background: #fff;
padding: 20px;
font-family: helvetica, arial, sans-serif;
font-size: 12pt;
line-height: 14pt;
-moz-box-shadow: #000 4px 4px 10px;
-webkit-box-shadow: #000 4px 4px 10px;
}
</style>
</head>
<body>
<div id="background">
- <% if thing.current_image %>
- <img src="<%= thing.current_image %>" />
+ <% if pie.current_image %>
+ <img src="<%= pie.current_image %>" />
<% end %>
</div>
<div id="content">
- <p><%= thing.current_place.description %></p>
+ <p><%= pie.current_place.description %></p>
<p>
- <% thing.current_place.paths.each do |place_name, label| %>
+ <% pie.current_place.paths.each do |place_name, label| %>
<%= " <a href='#{place_name}'>#{label}</a> " %>
<% end %>
</p>
</div>
</body>
</html>
diff --git a/views/image_page.erb b/views/image_page.erb
index b0e16fb..bb62690 100644
--- a/views/image_page.erb
+++ b/views/image_page.erb
@@ -1,57 +1,57 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title><%= $current %></title>
<style type="text/css" media="screen">
img.bg {
/* Set rules to fill background */
min-height: 100%;
min-width: 1024px;
/* Set up proportionate scaling */
width: 100%;
height: auto;
/* Set up positioning */
position: fixed;
top: 0;
left: 0;
}
@media screen and (max-width: 1024px){
img.bg {
left: 50%;
margin-left: -512px; }
}
div#content {
/* This is the only important rule */
/* We need our content to show up on top of the background */
position: relative;
/* These have no effect on the functionality */
width: 100%;
margin: 0 auto;
padding: 20px;
font-family: helvetica, arial, sans-serif;
font-size: 32pt;
line-height: 40pt;
text-align: center;
text-shadow: 1px 1px #fff;
}
</style>
</head>
<body>
-<img src="<%= current_image %>" class="bg" />
+<img src="<%= pie.current_image %>" class="bg" />
<div id="content">
- <p><%= current_place.description %></p>
+ <p><%= pie.current_place.description %></p>
</div>
</body>
</html>
|
blazingcloud/pie
|
78cdea091d96662c490c001a5fb7c6418003e08e
|
this is totally hacky, but it works, ugh
|
diff --git a/bin/pie b/bin/pie
index d33c722..cba0b4b 100755
--- a/bin/pie
+++ b/bin/pie
@@ -1,31 +1,38 @@
#!/usr/bin/env ruby
if RUBY_VERSION < "1.9.0"
puts "Error: pie requires Ruby 1.9, please use RVM."
exit
end
if ARGV.size == 0
puts "Usage: pie myfile"
exit
end
pie_file = ARGV.first
pie_file = "#{pie_file}.pie" unless File.exist?(pie_file)
unless File.exist?(pie_file)
puts "Unknown file #{ARGV.first}, please try again."
exit
end
begin
require 'pie'
rescue LoadError
$LOAD_PATH.unshift File.expand_path(File.join(File.dirname(__FILE__), "..", "lib"))
require 'pie'
end
+class PieThing
include Pie
-load pie_file
+end
+$thing = PieThing.new
+File.open(pie_file) do |f|
+$thing.instance_eval do
+ eval(f.read)
+end
+end
require 'pie_server'
WebApp.run! :port => 31415
diff --git a/lib/pie_server.rb b/lib/pie_server.rb
index c44efd8..d57a83f 100644
--- a/lib/pie_server.rb
+++ b/lib/pie_server.rb
@@ -1,20 +1,25 @@
require 'sinatra/base'
class WebApp < Sinatra::Base
set :root, File.join(File.expand_path(File.dirname(__FILE__)), "..")
get '/' do
"hello"
end
get '/:place_name' do
- name = params[:place_name].to_sym
- current_place(name) unless name.nil?
- puts "current place name is #{current_place.name}"
- puts "current place is #{current_place.description}"
- puts "--- skip out"; return if current_place.nil?
- puts "current links are #{current_place.paths.inspect}"
- puts "displaying template: #{template.inspect}"
- erb template
+ puts "============================================"
+ thing ||= $thing
+ thing ||= request.env["PIE_THING"]
+ puts "thing = #{thing.inspect}"
+ name = params[:place_name].to_sym
+ thing.current_place(name) unless name.nil?
+ puts "current place name is #{thing.current_place.name}"
+ puts "current place is #{thing.current_place.description}"
+ puts "--- skip out"; return if thing.current_place.nil?
+ puts "current links are #{thing.current_place.paths.inspect}"
+ puts "displaying template: #{thing.template.inspect}"
+ erb thing.template, {}, {:thing => thing}
end
+
end
diff --git a/views/game_screen.erb b/views/game_screen.erb
index 5438105..4537f6f 100644
--- a/views/game_screen.erb
+++ b/views/game_screen.erb
@@ -1,69 +1,69 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title><%= $current %></title>
<style type="text/css" media="screen">
body {
background: #000;
}
div#background {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%
}
div#background img {
/* Set up proportionate scaling */
width: auto;
height: 100%;
/* Set up positioning */
margin-left: auto;
margin-right: auto;
display: block;
}
div#content {
/* This is the only important rule */
/* We need our content to show up on top of the background */
position: relative;
/* These have no effect on the functionality */
width: 400px;
margin: 0 auto;
background: #fff;
padding: 20px;
font-family: helvetica, arial, sans-serif;
font-size: 12pt;
line-height: 14pt;
-moz-box-shadow: #000 4px 4px 10px;
-webkit-box-shadow: #000 4px 4px 10px;
}
</style>
</head>
<body>
<div id="background">
- <% if current_image %>
- <img src="<%= current_image %>" />
+ <% if thing.current_image %>
+ <img src="<%= thing.current_image %>" />
<% end %>
</div>
<div id="content">
- <p><%= current_place.description %></p>
+ <p><%= thing.current_place.description %></p>
<p>
- <% current_place.paths.each do |place_name, label| %>
+ <% thing.current_place.paths.each do |place_name, label| %>
<%= " <a href='#{place_name}'>#{label}</a> " %>
<% end %>
</p>
</div>
</body>
</html>
|
blazingcloud/pie
|
7f9d186de96950cbf35c26a38e405ec489aeb14d
|
fixed scoping issues with running Pie from rack
|
diff --git a/lib/pie.rb b/lib/pie.rb
index bf0543b..6c14897 100644
--- a/lib/pie.rb
+++ b/lib/pie.rb
@@ -1,78 +1,87 @@
module Pie
def self.[](key)
(@map ||= {})[key]
end
def self.[]=(key, value)
(@map ||= {})[key] = value
end
def self.language=(language)
@language = language
end
def self.localized(id)
@values ||= {
:japanese => {
:go_north => "Go North (in jp!)",
:go_south => "Go South (in jp!)",
:go_east => "Go East (in jp!)",
:go_west => "Go West (in jp!)"
},
:english => {
:go_north => "Go North",
:go_south => "Go South",
:go_east => "Go East",
:go_west => "Go West"
}
}
@values[@language || :english][id]
end
+
+ def self.places
+ Pie[:places] ||= {}
+ end
def template(name = nil)
if name
Pie[:template] = name.to_sym
else
Pie[:template] || :image_page
end
end
def images
Pie[:images] ||= {}
end
def image(image_maps)
images.merge!(image_maps)
end
def place(options)
- Place.new(options)
+ new_place = Place.new(options)
+ name = new_place.name
+ self.instance_eval %{
+ def #{name}
+ places[:#{name}]
+ end
+ }
+ places[new_place.name] = new_place
end
def current_place(name=nil)
- puts "current_place"
- puts places.inspect
if name
Pie[:current_place] = places[name.to_sym]
else
Pie[:current_place]
end
end
def current_image
images[current_place.name] if current_place
end
def places
- Pie[:places] ||= {}
+ Pie.places
end
def language(language)
Pie.language = language
end
end
require 'place'
require 'direction'
diff --git a/lib/place.rb b/lib/place.rb
index edc5f1e..1546609 100644
--- a/lib/place.rb
+++ b/lib/place.rb
@@ -1,47 +1,32 @@
class Pie::Place
attr_reader :name, :description, :paths
def initialize(options)
@paths = {}
extract_standard_options(options)
extract_name_and_description(options)
- build_place_method
- register_place
end
def to_s
@name
end
def path(nodes)
nodes.each do |place_name, direction|
paths[place_name] = direction
- places[place_name].paths[name] = direction.opposite unless !direction.respond_to?(:dead_end?) || direction.dead_end?
+ Pie.places[place_name].paths[name] = direction.opposite unless !direction.respond_to?(:dead_end?) || direction.dead_end?
end
end
private
def extract_name_and_description(options)
raise "You seem to have extras option in this place!" unless options.length == 1
@name = options.keys.first
@description = options.values.first
end
def extract_standard_options(options)
end
-
- def build_place_method
- Pie.module_eval %{
- def #{name}
- places[:#{name}]
- end
- }
- end
-
- def register_place
- places[name] = self
- end
-
end
diff --git a/pie.gemspec b/pie.gemspec
index d8cb948..9e15313 100644
--- a/pie.gemspec
+++ b/pie.gemspec
@@ -1,11 +1,11 @@
spec = Gem::Specification.new do |s|
s.name = 'pie'
s.authors = 'Sarah Allen, Sarah Mei, Rich Kilmer'
s.homepage = 'http://github.com/blazingcloud/pie'
- s.version = '0.2.2'
+ s.version = '0.2.6'
s.summary = 'Pie, a language for developing games and books'
s.files = Dir['lib/*.rb']+Dir['views/*.erb']+['README.md', 'MIT-LICENSE.txt', 'bin/pie']
s.bindir = 'bin'
s.executables << 'pie'
end
diff --git a/rack_example.ru b/rack_example.ru
new file mode 100644
index 0000000..7c79392
--- /dev/null
+++ b/rack_example.ru
@@ -0,0 +1,25 @@
+$LOAD_PATH.unshift File.expand_path(File.join(File.dirname(__FILE__), "."))
+$LOAD_PATH.unshift File.expand_path(File.join(File.dirname(__FILE__), "lib"))
+require 'lib/pie'
+
+# interactive example of calling pie from a rack app
+# run on the command line with
+# rackup rack_example.ru
+# then go to localhost:9292
+
+module Pie
+ class Rack
+ include Pie
+
+ def call(env)
+
+ place :park =>'this is a park'
+
+ ["200",{"Content-Type" => "text/plain"}, [park.description]]
+
+ end
+ end
+end
+
+run Pie::Rack.new
+
diff --git a/spec/pie_spec.rb b/spec/pie_spec.rb
index eb52c70..13ffd32 100644
--- a/spec/pie_spec.rb
+++ b/spec/pie_spec.rb
@@ -1,132 +1,159 @@
require File.join(File.expand_path(File.dirname(__FILE__)), "..", "lib", "pie")
-include Pie
+class Game
+ include Pie
+end
describe "baking pie" do
-
- describe "can access the current_place" do
- current_place.should == nil
- place ship:"this is a ship"
- current_place(:ship)
- current_place.should == ship
- place land:"this is land"
- current_place('land')
- current_place.should == land
+ before do
+ @game = Game.new
+ end
+ describe "included in a class" do
+
+ it "can access the current_place" do
+ @game.instance_eval do
+ current_place.should == nil
+ place ship:"this is a ship"
+ current_place(:ship)
+ current_place.should == ship
+ place land:"this is land"
+ current_place('land')
+ current_place.should == land
+ end
+ end
end
-
+
describe "with template" do
it "has a default template" do
- template.should == :image_page
+ @game.template.should == :image_page
end
it "can set an alternate template" do
- template :foo
- template.should == :foo
+ @game.instance_eval do
+ template :foo
+ template.should == :foo
+ end
end
end
describe "image declaration" do
it "can declare an image" do
- image ship:"http://foo.com/ship.png"
- images[:ship].should == "http://foo.com/ship.png"
+ @game.instance_eval do
+ image ship:"http://foo.com/ship.png"
+ images[:ship].should == "http://foo.com/ship.png"
+ end
end
it "can declare multiple image statements" do
- image ship:"http://foo.com/ship.png"
- image basket:"http://foo.com/basket.png"
- images[:ship].should == "http://foo.com/ship.png"
- images[:basket].should == "http://foo.com/basket.png"
+ @game.instance_eval do
+ image ship:"http://foo.com/ship.png"
+ image basket:"http://foo.com/basket.png"
+ images[:ship].should == "http://foo.com/ship.png"
+ images[:basket].should == "http://foo.com/basket.png"
+ end
end
it "can declare multiple images with one statement" do
- image ship:"http://foo.com/ship.png",
+ @game.instance_eval do
+ image ship:"http://foo.com/ship.png",
basket:"http://foo.com/basket.png"
- images[:ship].should == "http://foo.com/ship.png"
- images[:basket].should == "http://foo.com/basket.png"
+ images[:ship].should == "http://foo.com/ship.png"
+ images[:basket].should == "http://foo.com/basket.png"
+ end
end
end
describe "creates places" do
it "can create a place with extra options raises an error" do
lambda {
- place ship:"this is a ship", extra_option:"this"
+ @game.place ship:"this is a ship", extra_option:"this"
}.should raise_error
end
it "can create a place with a description" do
- place ship:"this is a ship"
- ship.should be_a(Place)
- ship.name.should == :ship
- ship.description.should == "this is a ship"
+ @game.instance_eval do
+ place ship:"this is a ship"
+ ship.class.should == Place
+ ship.name.should == :ship
+ ship.description.should == "this is a ship"
+ end
end
describe "with paths" do
before do
- place field:"You are in a large, grassy field. You see many trees to the north and a path to the east"
- place forest:"It is dark in the forest"
- place cliff_top:"The path ends at the top of a steep cliff"
- place cliff_bottom:"You walked off the cliff and fell to your death"
+ @game.instance_eval do
+ place field:"You are in a large, grassy field. You see many trees to the north and a path to the east"
+ place forest:"It is dark in the forest"
+ place cliff_top:"The path ends at the top of a steep cliff"
+ place cliff_bottom:"You walked off the cliff and fell to your death"
+ end
end
it "should have links between two places" do
- field.path forest:north
- field.paths.should == {forest:north}
- forest.paths.should == {field:south}
+ @game.instance_eval do
+ field.path forest:north
+ field.paths.should == {forest:north}
+ forest.paths.should == {field:south}
+ end
end
it "should have one way links" do
- cliff_top.path cliff_bottom:east!
- cliff_top.paths.should == {cliff_bottom:east}
- cliff_bottom.paths.should == {}
+ @game.instance_eval do
+ cliff_top.path cliff_bottom:east!
+ cliff_top.paths.should == {cliff_bottom:east}
+ cliff_bottom.paths.should == {}
+ end
end
it "should support simple strings" do
- field.path cliff_bottom:"flying leap"
- field.paths[:cliff_bottom].should == "flying leap"
+ @game.instance_eval do
+ field.path cliff_bottom:"flying leap"
+ field.paths[:cliff_bottom].should == "flying leap"
+ end
end
end
-
end
+
# describe "can access places" do
# before do
# ship description:"ookina fune"
# building description:"ookina biru"
# tower description:"ookina towa"
# end
#
# it "which are accessible by named key (symbol)" do
# ship = $pie.places[:ship]
# ship.should_not be_nil
# ship[:description].should == "ookina fune"
# end
#
# it "which are accessible by named key (string)" do
# ship = $pie.places["ship"]
# ship.should_not be_nil
# ship[:description].should == "ookina fune"
# end
#
# it "resulting in 2 places" do
# $pie.places.length.should == 3
# end
#
# it "and can find place after named place" do
# building = $pie.places.after(:ship)
# building.should_not be_nil
# building[:description].should == "ookina biru"
# end
#
# it "and finds nil after last place" do
# nothing = $pie.places.after(:tower)
# nothing.should be_nil
# end
#
# it "and can find place before named place" do
# building = $pie.places.before(:tower)
# building.should_not be_nil
# building[:description].should == "ookina biru"
# end
#
# it "and finds nil before first place" do
# nothing = $pie.places.before(:ship)
# nothing.should be_nil
# end
# end
end
|
blazingcloud/pie
|
3295dc610d4f16aa4452637b4f917750db1c6f6b
|
add dead_end back in but make it just a direction with no opposite, remove DeadEnd class
|
diff --git a/lib/direction.rb b/lib/direction.rb
index 23bacd9..1084ede 100644
--- a/lib/direction.rb
+++ b/lib/direction.rb
@@ -1,47 +1,58 @@
module Pie
class Direction < String
def opposite(opposite_name = nil)
if opposite_name
@opposite_name = opposite_name
else
@opposite_name
end
end
def dead_end?
@opposite_name.nil?
end
end
def direction(forward, back = nil)
dir = Direction.new(forward)
dir.opposite(back) if back
dir
end
+ def dead_end(name)
+ direction(name)
+ end
+
def north
@north ||= direction(Pie.localized(:go_north), Pie.localized(:go_south))
end
+
def south
@south ||= direction(Pie.localized(:go_south), Pie.localized(:go_north))
end
+
def east
@east ||= direction(Pie.localized(:go_east), Pie.localized(:go_west))
end
+
def west
@west ||= direction(Pie.localized(:go_west), Pie.localized(:go_east))
end
+
def north!
- direction(north)
+ dead_end(north)
end
+
def south!
- direction(south)
+ dead_end(south)
end
+
def east!
- direction(east)
+ dead_end(east)
end
+
def west!
- direction(west)
+ dead_end(west)
end
end
|
blazingcloud/pie
|
9ca7bbd3f7299ad9eb7a21b651ba76c723b3a301
|
udpated gemspec
|
diff --git a/pie.gemspec b/pie.gemspec
index a2dee35..9e5beda 100644
--- a/pie.gemspec
+++ b/pie.gemspec
@@ -1,11 +1,11 @@
spec = Gem::Specification.new do |s|
s.name = 'pie'
- s.authors = 'Sarah Allen, Sarah Mei'
+ s.authors = 'Sarah Allen, Sarah Mei, Rich Kilmer'
s.homepage = 'http://github.com/blazingcloud/pie'
- s.version = '0.2'
+ s.version = '0.2.1'
s.summary = 'Pie, a language for developing games and books'
s.files = Dir['lib/*']+Dir['bin/*']+Dir['views/*']+['README.md', 'MIT-LICENSE.txt']
s.bindir = 'bin'
s.executables << 'pie'
end
|
blazingcloud/pie
|
75dd64bb348ce19b5d867759b34fd12580b4fe71
|
simple strings for paths
|
diff --git a/lib/place.rb b/lib/place.rb
index daf9f19..edc5f1e 100644
--- a/lib/place.rb
+++ b/lib/place.rb
@@ -1,47 +1,47 @@
class Pie::Place
attr_reader :name, :description, :paths
def initialize(options)
@paths = {}
extract_standard_options(options)
extract_name_and_description(options)
build_place_method
register_place
end
def to_s
@name
end
def path(nodes)
nodes.each do |place_name, direction|
paths[place_name] = direction
- places[place_name].paths[name] = direction.opposite unless direction.dead_end?
+ places[place_name].paths[name] = direction.opposite unless !direction.respond_to?(:dead_end?) || direction.dead_end?
end
end
private
def extract_name_and_description(options)
raise "You seem to have extras option in this place!" unless options.length == 1
@name = options.keys.first
@description = options.values.first
end
def extract_standard_options(options)
end
def build_place_method
Pie.module_eval %{
def #{name}
places[:#{name}]
end
}
end
def register_place
places[name] = self
end
end
diff --git a/spec/pie_spec.rb b/spec/pie_spec.rb
index 3d4ecb5..eb52c70 100644
--- a/spec/pie_spec.rb
+++ b/spec/pie_spec.rb
@@ -1,127 +1,132 @@
require File.join(File.expand_path(File.dirname(__FILE__)), "..", "lib", "pie")
include Pie
describe "baking pie" do
describe "can access the current_place" do
current_place.should == nil
place ship:"this is a ship"
current_place(:ship)
current_place.should == ship
place land:"this is land"
current_place('land')
current_place.should == land
end
describe "with template" do
it "has a default template" do
template.should == :image_page
end
it "can set an alternate template" do
template :foo
template.should == :foo
end
end
describe "image declaration" do
it "can declare an image" do
image ship:"http://foo.com/ship.png"
images[:ship].should == "http://foo.com/ship.png"
end
it "can declare multiple image statements" do
image ship:"http://foo.com/ship.png"
image basket:"http://foo.com/basket.png"
images[:ship].should == "http://foo.com/ship.png"
images[:basket].should == "http://foo.com/basket.png"
end
it "can declare multiple images with one statement" do
image ship:"http://foo.com/ship.png",
basket:"http://foo.com/basket.png"
images[:ship].should == "http://foo.com/ship.png"
images[:basket].should == "http://foo.com/basket.png"
end
end
describe "creates places" do
it "can create a place with extra options raises an error" do
lambda {
place ship:"this is a ship", extra_option:"this"
}.should raise_error
end
it "can create a place with a description" do
place ship:"this is a ship"
ship.should be_a(Place)
ship.name.should == :ship
ship.description.should == "this is a ship"
end
describe "with paths" do
before do
place field:"You are in a large, grassy field. You see many trees to the north and a path to the east"
place forest:"It is dark in the forest"
place cliff_top:"The path ends at the top of a steep cliff"
place cliff_bottom:"You walked off the cliff and fell to your death"
end
it "should have links between two places" do
field.path forest:north
field.paths.should == {forest:north}
forest.paths.should == {field:south}
end
it "should have one way links" do
cliff_top.path cliff_bottom:east!
cliff_top.paths.should == {cliff_bottom:east}
cliff_bottom.paths.should == {}
end
+
+ it "should support simple strings" do
+ field.path cliff_bottom:"flying leap"
+ field.paths[:cliff_bottom].should == "flying leap"
+ end
end
end
# describe "can access places" do
# before do
# ship description:"ookina fune"
# building description:"ookina biru"
# tower description:"ookina towa"
# end
#
# it "which are accessible by named key (symbol)" do
# ship = $pie.places[:ship]
# ship.should_not be_nil
# ship[:description].should == "ookina fune"
# end
#
# it "which are accessible by named key (string)" do
# ship = $pie.places["ship"]
# ship.should_not be_nil
# ship[:description].should == "ookina fune"
# end
#
# it "resulting in 2 places" do
# $pie.places.length.should == 3
# end
#
# it "and can find place after named place" do
# building = $pie.places.after(:ship)
# building.should_not be_nil
# building[:description].should == "ookina biru"
# end
#
# it "and finds nil after last place" do
# nothing = $pie.places.after(:tower)
# nothing.should be_nil
# end
#
# it "and can find place before named place" do
# building = $pie.places.before(:tower)
# building.should_not be_nil
# building[:description].should == "ookina biru"
# end
#
# it "and finds nil before first place" do
# nothing = $pie.places.before(:ship)
# nothing.should be_nil
# end
# end
end
|
blazingcloud/pie
|
dd0a4de3e7745a231d98480ee4060b462447cc80
|
git ignore gem file
|
diff --git a/.gitignore b/.gitignore
index 485dee6..11401d9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1 +1,3 @@
.idea
+*~
+*.gem
|
blazingcloud/pie
|
e54a80958349b90b35d0535dcfba8c2cca6d3164
|
changed port number to 31415
|
diff --git a/README b/README
index ffc9eab..de7e110 100644
--- a/README
+++ b/README
@@ -1,49 +1,49 @@
# Pie
A game development DSL, inspired by Yasuko Ohba's Ruby Kaigi talk and a late night conversation with @knowtheory, @wycats, @sarahmei and @ultrasaurus.
Pie requires Ruby 1.9, because it is so cool.
## Examples
### Game
pie game.pie
then go to:
- http://localhost:4567/park
+ http://localhost:31415/park
Follow links to wander around the game world. Yes, that is all there is right now.
### Book -- NOT WORKING YET
There is a sample in book.rb. To use it:
pie book.pie
then go to:
- http://localhost:4567/ship
- http://localhost:4567/building
- http://localhost:4567/tower
+ http://localhost:31415/ship
+ http://localhost:31415/building
+ http://localhost:31415/tower
Someday there will be UI to change pages.
## Issues?
Bugs and features are tracked here: http://www.pivotaltracker.com/projects/115060
I want to try to resist adding any new features until we have no bugs and kid-friendly error messages. Help is welcome. Feel free to fork and submit pull requests or just tweet or email ideas.
## Pie Contributors
-Core team (in order of appearance)
+Core team (in order of appearance)
* Sarah Allen
* Sarah Mei
* Rich Kilmer
Contributors
* Dan Steinicke
* Akira Matsuda
* Chad Fowler
diff --git a/bin/pie b/bin/pie
index 6367f6f..d33c722 100755
--- a/bin/pie
+++ b/bin/pie
@@ -1,31 +1,31 @@
#!/usr/bin/env ruby
if RUBY_VERSION < "1.9.0"
puts "Error: pie requires Ruby 1.9, please use RVM."
exit
end
if ARGV.size == 0
puts "Usage: pie myfile"
exit
end
pie_file = ARGV.first
pie_file = "#{pie_file}.pie" unless File.exist?(pie_file)
unless File.exist?(pie_file)
puts "Unknown file #{ARGV.first}, please try again."
exit
end
begin
require 'pie'
rescue LoadError
$LOAD_PATH.unshift File.expand_path(File.join(File.dirname(__FILE__), "..", "lib"))
require 'pie'
end
include Pie
load pie_file
require 'pie_server'
-WebApp.run!
\ No newline at end of file
+WebApp.run! :port => 31415
diff --git a/lib/pie_server.rb b/lib/pie_server.rb
index b90c444..c44efd8 100644
--- a/lib/pie_server.rb
+++ b/lib/pie_server.rb
@@ -1,21 +1,20 @@
require 'sinatra/base'
class WebApp < Sinatra::Base
set :root, File.join(File.expand_path(File.dirname(__FILE__)), "..")
get '/' do
"hello"
end
get '/:place_name' do
name = params[:place_name].to_sym
- puts "going to place with name #{name}"
current_place(name) unless name.nil?
puts "current place name is #{current_place.name}"
puts "current place is #{current_place.description}"
puts "--- skip out"; return if current_place.nil?
puts "current links are #{current_place.paths.inspect}"
puts "displaying template: #{template.inspect}"
erb template
end
end
|
blazingcloud/pie
|
9d28c666a25393423f8e7937ce9ec85406f5488a
|
added pie executable, version = 0.2
|
diff --git a/pie.gemspec b/pie.gemspec
index c0f54d1..a2dee35 100644
--- a/pie.gemspec
+++ b/pie.gemspec
@@ -1,9 +1,11 @@
spec = Gem::Specification.new do |s|
s.name = 'pie'
s.authors = 'Sarah Allen, Sarah Mei'
s.homepage = 'http://github.com/blazingcloud/pie'
- s.version = '0.1.3'
+ s.version = '0.2'
s.summary = 'Pie, a language for developing games and books'
- s.files = Dir['lib/*']+Dir['views/*']+['README.md', 'MIT-LICENSE.txt']
+ s.files = Dir['lib/*']+Dir['bin/*']+Dir['views/*']+['README.md', 'MIT-LICENSE.txt']
+ s.bindir = 'bin'
+ s.executables << 'pie'
end
|
blazingcloud/pie
|
9aba2b0637e9d7e165ccf851218ecaa4ce913cf2
|
changed file extension to .pie, updated README
|
diff --git a/README b/README
index 393a3d5..ffc9eab 100644
--- a/README
+++ b/README
@@ -1,47 +1,49 @@
# Pie
A game development DSL, inspired by Yasuko Ohba's Ruby Kaigi talk and a late night conversation with @knowtheory, @wycats, @sarahmei and @ultrasaurus.
Pie requires Ruby 1.9, because it is so cool.
## Examples
-### Book
-There is a sample in book.rb. To use it:
- ruby book.rb
+### Game
+
+ pie game.pie
then go to:
- http://localhost:4567/ship
- http://localhost:4567/building
- http://localhost:4567/tower
+ http://localhost:4567/park
-Someday there will be UI to change pages.
+Follow links to wander around the game world. Yes, that is all there is right now.
-### Game
+### Book -- NOT WORKING YET
+
+There is a sample in book.rb. To use it:
- ruby game.rb
+ pie book.pie
then go to:
- http://localhost:4567/park
+ http://localhost:4567/ship
+ http://localhost:4567/building
+ http://localhost:4567/tower
-Follow links to wander around the game world. Yes, that is all there is right now.
+Someday there will be UI to change pages.
## Issues?
Bugs and features are tracked here: http://www.pivotaltracker.com/projects/115060
I want to try to resist adding any new features until we have no bugs and kid-friendly error messages. Help is welcome. Feel free to fork and submit pull requests or just tweet or email ideas.
## Pie Contributors
Core team (in order of appearance)
* Sarah Allen
* Sarah Mei
* Rich Kilmer
Contributors
* Dan Steinicke
* Akira Matsuda
* Chad Fowler
diff --git a/book.rb b/book.pie
similarity index 100%
rename from book.rb
rename to book.pie
diff --git a/game.rb b/game.pie
similarity index 100%
rename from game.rb
rename to game.pie
diff --git a/lib/pie.rb b/lib/pie.rb
index 9c59901..819dd48 100644
--- a/lib/pie.rb
+++ b/lib/pie.rb
@@ -1,50 +1,52 @@
module Pie
def self.[](key)
(@map ||= {})[key]
end
def self.[]=(key, value)
(@map ||= {})[key] = value
end
def template(name = nil)
if name
Pie[:template] = name.to_sym
else
Pie[:template] || :image_page
end
end
def images
Pie[:images] ||= {}
end
def image(image_maps)
images.merge!(image_maps)
end
def place(options)
Place.new(options)
end
def current_place(name=nil)
+ puts "current_place"
+ puts places.inspect
if name
Pie[:current_place] = places[name.to_sym]
else
Pie[:current_place]
end
end
def current_image
images[current_place.name] if current_place
end
def places
Pie[:places] ||= {}
end
end
require 'place'
-require 'direction'
\ No newline at end of file
+require 'direction'
diff --git a/lib/pie_server.rb b/lib/pie_server.rb
index c44efd8..b90c444 100644
--- a/lib/pie_server.rb
+++ b/lib/pie_server.rb
@@ -1,20 +1,21 @@
require 'sinatra/base'
class WebApp < Sinatra::Base
set :root, File.join(File.expand_path(File.dirname(__FILE__)), "..")
get '/' do
"hello"
end
get '/:place_name' do
name = params[:place_name].to_sym
+ puts "going to place with name #{name}"
current_place(name) unless name.nil?
puts "current place name is #{current_place.name}"
puts "current place is #{current_place.description}"
puts "--- skip out"; return if current_place.nil?
puts "current links are #{current_place.paths.inspect}"
puts "displaying template: #{template.inspect}"
erb template
end
end
|
blazingcloud/pie
|
d41d4875435231bbcf17ddf138d0245ebcdb2ead
|
pie_app_spec passes but book.rb doesn't work still
|
diff --git a/book.rb b/book.rb
index 3e9a089..5cec5a9 100644
--- a/book.rb
+++ b/book.rb
@@ -1,17 +1,11 @@
#encoding:UTF-8
-$LOAD_PATH << File.dirname(__FILE__)
-require 'lib/pie'
-make_pie do
- create_places do
- ship description:"大ããªè¹"
- building description:"ookina biru"
- tower description:"ookina tawaa"
- end
+place ship:"大ããªè¹"
+place building:"ookina biru"
+place tower:"ookina tawaa"
- image ship:"images/big_ship.jpg",
- building:"images/building.jpg",
- tower:"images/tokyo_tower.jpg"
-end
+image ship:"images/big_ship.jpg",
+ building:"images/building.jpg",
+ tower:"images/tokyo_tower.jpg"
diff --git a/spec/pie_app_spec.rb b/spec/pie_app_spec.rb
index 0619bff..7a85481 100644
--- a/spec/pie_app_spec.rb
+++ b/spec/pie_app_spec.rb
@@ -1,54 +1,43 @@
$LOAD_PATH << File.join(File.expand_path(File.dirname(__FILE__)), "..", "lib")
require 'pie'
+require 'pie_server'
require 'capybara'
require 'capybara/dsl'
describe "app created with pie" do
include Capybara
+ include Pie
before do
- Capybara.app = Pie::WebApp
+ Capybara.app = WebApp
end
it "should say hello for the root path" do
visit '/'
page.should have_content "hello"
end
describe "with one place and an image" do
before do
- puts "in before"
- make_pie do
- puts "in make pie"
- create_places do
- puts "in create places"
- ship description:"ookina fune"
- puts "made a ship!"
- end
- puts "about to add an image"
- image ship:"images/big_ship.jpg"
- end
+ place ship:"ookina fune"
+ image ship:"images/big_ship.jpg"
end
it "should display the ship page" do
visit '/ship'
page.should have_content('ookina fune')
end
end
describe "with two places and images" do
before do
- make_pie do
- create_places do
- ship description:"ookina fune"
- building description:"ookina biru"
- end
- image ship:"images/big_ship.jpg"
- image building:"images/building.jpg"
- end
+ place ship:"ookina fune"
+ place building:"ookina biru"
+ image ship:"images/big_ship.jpg"
+ image building:"images/building.jpg"
end
it "should display the next button" do
visit '/ship'
page.should have_content('next')
end
end
end
|
blazingcloud/pie
|
4a2a71fb23357a0b06d84b44f2cbfa9e7706ba25
|
refactor for new api
|
diff --git a/book.rb b/book.rb
index 3e9a089..3b54a6b 100644
--- a/book.rb
+++ b/book.rb
@@ -1,17 +1,13 @@
#encoding:UTF-8
-$LOAD_PATH << File.dirname(__FILE__)
-require 'lib/pie'
-make_pie do
- create_places do
- ship description:"大ããªè¹"
- building description:"ookina biru"
- tower description:"ookina tawaa"
- end
+template :game_screen
- image ship:"images/big_ship.jpg",
- building:"images/building.jpg",
- tower:"images/tokyo_tower.jpg"
-end
+place ship:"大ããªè¹"
+place building:"ookina biru"
+place tower:"ookina tawaa"
+
+image ship:"images/big_ship.jpg",
+ building:"images/building.jpg",
+ tower:"images/tokyo_tower.jpg"
|
blazingcloud/pie
|
829cce3cba03a92cc6a186067bc6013a29468477
|
change to new api
|
diff --git a/views/full_screen.erb b/views/full_screen.erb
index 9412542..e38d3f0 100644
--- a/views/full_screen.erb
+++ b/views/full_screen.erb
@@ -1,63 +1,63 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
- <title><%= $current %></title>
+ <title><%= current_place.name %></title>
<style type="text/css" media="screen">
img.bg {
/* Set rules to fill background */
min-height: 100%;
min-width: 1024px;
/* Set up proportionate scaling */
width: 100%;
height: auto;
/* Set up positioning */
position: fixed;
top: 0;
left: 0;
}
@media screen and (max-width: 1024px){
img.bg {
left: 50%;
margin-left: -512px; }
}
div#content {
/* This is the only important rule */
/* We need our content to show up on top of the background */
position: relative;
/* These have no effect on the functionality */
width: 80%;
margin: 0 auto;
background: #fff;
padding: 20px;
font-family: helvetica, arial, sans-serif;
font-size: 12pt;
line-height: 14pt;
-moz-box-shadow: #000 4px 4px 10px;
-webkit-box-shadow: #000 4px 4px 10px;
}
</style>
</head>
<body>
-<img src="<%= $pie.current_image %>" class="bg" />
+<img src="<%= current_image %>" class="bg" />
<div id="content">
- <p><%= $pie.current_description %></p>
+ <p><%= current_place.description %></p>
<p>
- <% $pie.places[$current].links.each do |place_name, label| %>
- <%= " <a href='#{place_name}'>#{label.to_s}</a> " %>
+ <% current_place.paths.each do |place_name, label| %>
+ <%= " <a href='#{place_name}'>#{label}</a> " %>
<% end %>
</p>
</div>
</body>
</html>
diff --git a/views/image_page.erb b/views/image_page.erb
index 2464fdf..b0e16fb 100644
--- a/views/image_page.erb
+++ b/views/image_page.erb
@@ -1,57 +1,57 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title><%= $current %></title>
<style type="text/css" media="screen">
img.bg {
/* Set rules to fill background */
min-height: 100%;
min-width: 1024px;
/* Set up proportionate scaling */
width: 100%;
height: auto;
/* Set up positioning */
position: fixed;
top: 0;
left: 0;
}
@media screen and (max-width: 1024px){
img.bg {
left: 50%;
margin-left: -512px; }
}
div#content {
/* This is the only important rule */
/* We need our content to show up on top of the background */
position: relative;
/* These have no effect on the functionality */
width: 100%;
margin: 0 auto;
padding: 20px;
font-family: helvetica, arial, sans-serif;
font-size: 32pt;
line-height: 40pt;
text-align: center;
text-shadow: 1px 1px #fff;
}
</style>
</head>
<body>
-<img src="<%= $pie.current_image %>" class="bg" />
+<img src="<%= current_image %>" class="bg" />
<div id="content">
- <p><%= $pie.current_description %></p>
+ <p><%= current_place.description %></p>
</div>
</body>
</html>
|
blazingcloud/pie
|
e2ae32e2311a3f398b7d1959fa680195ba5093db
|
add basic language support. used in directions currently (for n/s/e/w). to use: language :japanese [note: default is :english]. see pie.rb for the localizable strings.
|
diff --git a/lib/direction.rb b/lib/direction.rb
index 65d35a7..23bacd9 100644
--- a/lib/direction.rb
+++ b/lib/direction.rb
@@ -1,46 +1,47 @@
module Pie
-
+
class Direction < String
+
def opposite(opposite_name = nil)
if opposite_name
@opposite_name = opposite_name
else
@opposite_name
end
end
def dead_end?
@opposite_name.nil?
end
end
def direction(forward, back = nil)
dir = Direction.new(forward)
dir.opposite(back) if back
dir
end
def north
- @north ||= direction('Go North', 'Go South')
+ @north ||= direction(Pie.localized(:go_north), Pie.localized(:go_south))
end
def south
- @south ||= direction('Go South', 'Go North')
+ @south ||= direction(Pie.localized(:go_south), Pie.localized(:go_north))
end
def east
- @east ||= direction('Go East', 'Go West')
+ @east ||= direction(Pie.localized(:go_east), Pie.localized(:go_west))
end
def west
- @west ||= direction('Go West', 'Go East')
+ @west ||= direction(Pie.localized(:go_west), Pie.localized(:go_east))
end
def north!
direction(north)
end
def south!
direction(south)
end
def east!
direction(east)
end
def west!
direction(west)
end
end
diff --git a/lib/pie.rb b/lib/pie.rb
index 9c59901..c3479e7 100644
--- a/lib/pie.rb
+++ b/lib/pie.rb
@@ -1,50 +1,76 @@
module Pie
def self.[](key)
(@map ||= {})[key]
end
def self.[]=(key, value)
(@map ||= {})[key] = value
end
+
+ def self.language=(language)
+ @language = language
+ end
+
+ def self.localized(id)
+ @values ||= {
+ :japanese => {
+ :go_north => "Go North (in jp!)",
+ :go_south => "Go South (in jp!)",
+ :go_east => "Go East (in jp!)",
+ :go_west => "Go West (in jp!)"
+ },
+ :english => {
+ :go_north => "Go North",
+ :go_south => "Go South",
+ :go_east => "Go East",
+ :go_west => "Go West"
+ }
+ }
+ @values[@language || :english][id]
+ end
def template(name = nil)
if name
Pie[:template] = name.to_sym
else
Pie[:template] || :image_page
end
end
def images
Pie[:images] ||= {}
end
def image(image_maps)
images.merge!(image_maps)
end
def place(options)
Place.new(options)
end
def current_place(name=nil)
if name
Pie[:current_place] = places[name.to_sym]
else
Pie[:current_place]
end
end
def current_image
images[current_place.name] if current_place
end
def places
Pie[:places] ||= {}
end
+ def language(language)
+ Pie.language = language
+ end
+
end
require 'place'
require 'direction'
\ No newline at end of file
|
blazingcloud/pie
|
4b159c598bfd1c323c4662b8e110e836aa8c4170
|
refactor direction to be a dead end if it has no opposite direction (removing the need for DeadEnd. new usage is: direction(up
|
diff --git a/lib/direction.rb b/lib/direction.rb
index 8ccee0f..65d35a7 100644
--- a/lib/direction.rb
+++ b/lib/direction.rb
@@ -1,56 +1,46 @@
module Pie
- class DeadEnd < String
- def dead_end?
- true
- end
- end
-
class Direction < String
- def opposite(display_name = nil)
- if display_name
- @display_name = display_name
+ def opposite(opposite_name = nil)
+ if opposite_name
+ @opposite_name = opposite_name
else
- @display_name
+ @opposite_name
end
end
def dead_end?
- false
+ @opposite_name.nil?
end
end
- def direction(forward, back)
+ def direction(forward, back = nil)
dir = Direction.new(forward)
- dir.opposite(back)
+ dir.opposite(back) if back
dir
end
def north
@north ||= direction('Go North', 'Go South')
end
-
def south
@south ||= direction('Go South', 'Go North')
end
def east
@east ||= direction('Go East', 'Go West')
end
def west
@west ||= direction('Go West', 'Go East')
end
- def dead_end(name)
- DeadEnd.new(name)
- end
def north!
- dead_end(north)
+ direction(north)
end
def south!
- dead_end(south)
+ direction(south)
end
def east!
- dead_end(east)
+ direction(east)
end
def west!
- dead_end(west)
+ direction(west)
end
end
|
blazingcloud/pie
|
5edb731dce1347906ee6d44877d79c5556ece70d
|
added license and gem spec
|
diff --git a/MIT-LICENSE.txt b/MIT-LICENSE.txt
new file mode 100644
index 0000000..832a7a5
--- /dev/null
+++ b/MIT-LICENSE.txt
@@ -0,0 +1,20 @@
+Copyright (c) 2010 Sarah Allen
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
diff --git a/pie.gemspec b/pie.gemspec
new file mode 100644
index 0000000..c0f54d1
--- /dev/null
+++ b/pie.gemspec
@@ -0,0 +1,9 @@
+
+spec = Gem::Specification.new do |s|
+ s.name = 'pie'
+ s.authors = 'Sarah Allen, Sarah Mei'
+ s.homepage = 'http://github.com/blazingcloud/pie'
+ s.version = '0.1.3'
+ s.summary = 'Pie, a language for developing games and books'
+ s.files = Dir['lib/*']+Dir['views/*']+['README.md', 'MIT-LICENSE.txt']
+end
|
blazingcloud/pie
|
0398b09eb11204a6b7deba39d997c0b8ac2b8edd
|
gogaruco rafactor. rewrote all of pie and the specs and updated game.rb to reflect the new syntax
|
diff --git a/bin/pie b/bin/pie
new file mode 100755
index 0000000..6367f6f
--- /dev/null
+++ b/bin/pie
@@ -0,0 +1,31 @@
+#!/usr/bin/env ruby
+if RUBY_VERSION < "1.9.0"
+ puts "Error: pie requires Ruby 1.9, please use RVM."
+ exit
+end
+
+if ARGV.size == 0
+ puts "Usage: pie myfile"
+ exit
+end
+
+pie_file = ARGV.first
+pie_file = "#{pie_file}.pie" unless File.exist?(pie_file)
+
+unless File.exist?(pie_file)
+ puts "Unknown file #{ARGV.first}, please try again."
+ exit
+end
+
+begin
+ require 'pie'
+rescue LoadError
+ $LOAD_PATH.unshift File.expand_path(File.join(File.dirname(__FILE__), "..", "lib"))
+ require 'pie'
+end
+
+include Pie
+load pie_file
+
+require 'pie_server'
+WebApp.run!
\ No newline at end of file
diff --git a/game.rb b/game.rb
index be1ce39..42faded 100644
--- a/game.rb
+++ b/game.rb
@@ -1,23 +1,14 @@
-$LOAD_PATH << File.dirname(__FILE__)
-require 'lib/pie'
+template :game_screen
-make_pie do
- template :game_screen
+place park:"You are in a park. You see trees to the north and a path to the east"
+place trees:"You are in a Japanese garden."
+place river_edge:"The path ends at a river"
+place in_the_river:"You walk into the river and drown."
- create_places do
- park description:"You are in a park. You see trees to the north and a path to the east"
- trees description:"You are in a Japanese garden."
- river_edge description:"The path ends at a river"
- in_the_river description:"You walk into the river and drown."
- end
+park.path trees:north, river_edge:east
+river_edge.path in_the_river:east!
- map do
- path(park:"North", trees:"South")
- path(park:"East", river_edge:"West")
- path(river_edge:"East", in_the_river:NO_WAY_BACK)
- end
+image park:"images/park.JPG"
+image river_edge:"images/water.JPG"
+image trees:"images/trees.JPG"
- image park:"images/park.JPG"
- image river_edge:"images/water.JPG"
- image trees:"images/trees.JPG"
-end
diff --git a/lib/direction.rb b/lib/direction.rb
new file mode 100644
index 0000000..8ccee0f
--- /dev/null
+++ b/lib/direction.rb
@@ -0,0 +1,56 @@
+module Pie
+
+ class DeadEnd < String
+ def dead_end?
+ true
+ end
+ end
+
+ class Direction < String
+ def opposite(display_name = nil)
+ if display_name
+ @display_name = display_name
+ else
+ @display_name
+ end
+ end
+ def dead_end?
+ false
+ end
+ end
+
+ def direction(forward, back)
+ dir = Direction.new(forward)
+ dir.opposite(back)
+ dir
+ end
+
+ def north
+ @north ||= direction('Go North', 'Go South')
+ end
+
+ def south
+ @south ||= direction('Go South', 'Go North')
+ end
+ def east
+ @east ||= direction('Go East', 'Go West')
+ end
+ def west
+ @west ||= direction('Go West', 'Go East')
+ end
+ def dead_end(name)
+ DeadEnd.new(name)
+ end
+ def north!
+ dead_end(north)
+ end
+ def south!
+ dead_end(south)
+ end
+ def east!
+ dead_end(east)
+ end
+ def west!
+ dead_end(west)
+ end
+end
diff --git a/lib/pie.rb b/lib/pie.rb
index 8877d3d..9c59901 100644
--- a/lib/pie.rb
+++ b/lib/pie.rb
@@ -1,160 +1,50 @@
-require 'sinatra/base'
-#puts "----------------- Ruby version = #{RUBY_VERSION}"
-#raise ScriptError, "Pie requires Ruby 1.9 or higher" if RUBY_VERSION < "1.9.0"
-NO_WAY_BACK = ""
-class Pie
+module Pie
-
- attr_accessor :places
- attr_accessor :images
- attr_accessor :default_template
-
- def initialize
- @default_template = :image_page
- @places = Places.new
- @map = Map.new(@places)
- end
-
- class WebApp < Sinatra::Base
- set :root, File.join(File.expand_path(File.dirname(__FILE__)), "..")
-
- get '/' do
- "hello"
- end
-
- get '/:place_name' do
- name = params[:place_name].to_sym
- $current = name unless name.nil?
- puts "current place name is #{$current}"
- puts "current place is #{$pie.places[$current]}"
- puts "--- skip out"; return if $pie.places[$current].nil?
- puts "current links are #{$pie.places[$current].links.inspect}"
- puts "displaying template: #{$pie.default_template.inspect}"
- erb $pie.default_template
- end
- end
-
- at_exit { WebApp.run! if !$0.include?("spec")}
-
- class Map
-
- def initialize places
- @places = places
- end
-
- def path endpoints
- puts "---> path #{endpoints.inspect}"
- puts @places.inspect
- #if h.size != 2
- # return puts "path must have two and only two endpoints."
- #end
- start_place_key, end_place_key = endpoints.keys
- label_for_end, label_for_start = endpoints.values
-
- start_place = @places[start_place_key]
- end_place = @places[end_place_key]
- raise ArgumentError, "there is no place named '#{start_place_key}'" if start_place.nil?
- raise ArgumentError, "there is no place named '#{end_place_key}'" if end_place.nil?
-
- start_place[:links][end_place_key] = label_for_end unless label_for_end.empty?
- end_place[:links][start_place_key] = label_for_start unless label_for_start.empty?
- end
+ def self.[](key)
+ (@map ||= {})[key]
end
- class Place < Hash
- def initialize
- self[:links] = {}
- end
- def links
- result = self[:links]
- end
-
+ def self.[]=(key, value)
+ (@map ||= {})[key] = value
end
-
- class Places < Hash
- def method_missing name, options = {}
- unless options.is_a? Hash
- puts "options for creating a place must have key and value"
- return
- end
- puts "making a #{name} with #{options.inspect}"
- place = Place.new
- place.merge! options
- self[name.to_sym] = place
- end
-
- def [] string_or_symbol
- super string_or_symbol.to_sym
- end
-
- def after(place_name)
- index = keys.index(place_name.to_sym)
- next_place_name = keys[index + 1]
- self[next_place_name] unless next_place_name.nil?
- end
-
- def before(place_name)
- index = keys.index(place_name.to_sym)
- index = index - 1
- if index < 0
- nil
- else
- prev_place_name = keys[index]
- self[prev_place_name]
- end
+
+ def template(name = nil)
+ if name
+ Pie[:template] = name.to_sym
+ else
+ Pie[:template] || :image_page
end
end
-
- def template(template_name)
- puts "--> set default template #{template_name.to_sym}"
- @default_template = template_name.to_sym
+
+ def images
+ Pie[:images] ||= {}
end
-
- def create_places(&block)
- @places.instance_eval(&block)
+
+ def image(image_maps)
+ images.merge!(image_maps)
end
- def map(&block)
- puts "-------- creating map --------"
- @map.instance_eval(&block)
+ def place(options)
+ Place.new(options)
end
-
- def image(image_hash)
- @images ||= {}
- puts "--- set image"
- puts image_hash.inspect
- @images.merge!(image_hash)
+
+ def current_place(name=nil)
+ if name
+ Pie[:current_place] = places[name.to_sym]
+ else
+ Pie[:current_place]
+ end
end
-
- def current_image
- puts "------- current_image"
- puts $current.inspect
- puts @images.inspect
- @images[$current.to_sym]
+
+ def current_image
+ images[current_place.name] if current_place
end
-
- def current_description
- puts "------- current_description"
- puts $current.inspect
- place = @places[$current.to_sym]
- puts @place.inspect
- place[:description] unless place.nil?
+
+ def places
+ Pie[:places] ||= {}
end
+
end
-def make_pie(&block)
- puts "-------------------------- making pie ---------------------------- "
- $pie = Pie.new
- $pie.instance_eval(&block)
- puts "-------------------------- pie complete ---------------------------- "
-end
-
-def more_pie(&block)
- puts "-------------------------- more pie ---------------------------- "
- if $pie.nil?
- puts "How can you make more pie when you haven't made any pie yet?"
- return
- end
- $pie.instance_eval(&block)
- puts "-------------------------- pie complete ---------------------------- "
-end
+require 'place'
+require 'direction'
\ No newline at end of file
diff --git a/lib/pie_server.rb b/lib/pie_server.rb
new file mode 100644
index 0000000..c44efd8
--- /dev/null
+++ b/lib/pie_server.rb
@@ -0,0 +1,20 @@
+require 'sinatra/base'
+
+class WebApp < Sinatra::Base
+ set :root, File.join(File.expand_path(File.dirname(__FILE__)), "..")
+
+ get '/' do
+ "hello"
+ end
+
+ get '/:place_name' do
+ name = params[:place_name].to_sym
+ current_place(name) unless name.nil?
+ puts "current place name is #{current_place.name}"
+ puts "current place is #{current_place.description}"
+ puts "--- skip out"; return if current_place.nil?
+ puts "current links are #{current_place.paths.inspect}"
+ puts "displaying template: #{template.inspect}"
+ erb template
+ end
+end
diff --git a/lib/place.rb b/lib/place.rb
new file mode 100644
index 0000000..daf9f19
--- /dev/null
+++ b/lib/place.rb
@@ -0,0 +1,47 @@
+class Pie::Place
+
+ attr_reader :name, :description, :paths
+
+ def initialize(options)
+ @paths = {}
+ extract_standard_options(options)
+ extract_name_and_description(options)
+ build_place_method
+ register_place
+ end
+
+ def to_s
+ @name
+ end
+
+ def path(nodes)
+ nodes.each do |place_name, direction|
+ paths[place_name] = direction
+ places[place_name].paths[name] = direction.opposite unless direction.dead_end?
+ end
+ end
+
+ private
+
+ def extract_name_and_description(options)
+ raise "You seem to have extras option in this place!" unless options.length == 1
+ @name = options.keys.first
+ @description = options.values.first
+ end
+
+ def extract_standard_options(options)
+ end
+
+ def build_place_method
+ Pie.module_eval %{
+ def #{name}
+ places[:#{name}]
+ end
+ }
+ end
+
+ def register_place
+ places[name] = self
+ end
+
+end
diff --git a/spec/pie_spec.rb b/spec/pie_spec.rb
index 8f70f34..3d4ecb5 100644
--- a/spec/pie_spec.rb
+++ b/spec/pie_spec.rb
@@ -1,150 +1,127 @@
require File.join(File.expand_path(File.dirname(__FILE__)), "..", "lib", "pie")
-describe "making pie" do
+include Pie
+
+describe "baking pie" do
+
+ describe "can access the current_place" do
+ current_place.should == nil
+ place ship:"this is a ship"
+ current_place(:ship)
+ current_place.should == ship
+ place land:"this is land"
+ current_place('land')
+ current_place.should == land
+ end
+
describe "with template" do
it "has a default template" do
- make_pie {}
- $pie.default_template.should == :image_page
+ template.should == :image_page
end
it "can set an alternate template" do
- make_pie do
- template :foo
- end
- $pie.default_template.should == :foo
+ template :foo
+ template.should == :foo
end
end
describe "image declaration" do
it "can declare an image" do
- make_pie do
- image ship:"http://foo.com/ship.png"
- end
- $pie.images[:ship].should == "http://foo.com/ship.png"
+ image ship:"http://foo.com/ship.png"
+ images[:ship].should == "http://foo.com/ship.png"
end
it "can declare multiple image statements" do
- make_pie do
- image ship:"http://foo.com/ship.png"
- image basket:"http://foo.com/basket.png"
- end
- $pie.images[:ship].should == "http://foo.com/ship.png"
- $pie.images[:basket].should == "http://foo.com/basket.png"
+ image ship:"http://foo.com/ship.png"
+ image basket:"http://foo.com/basket.png"
+ images[:ship].should == "http://foo.com/ship.png"
+ images[:basket].should == "http://foo.com/basket.png"
end
it "can declare multiple images with one statement" do
- make_pie do
- image ship:"http://foo.com/ship.png",
- basket:"http://foo.com/basket.png"
- end
- $pie.images[:ship].should == "http://foo.com/ship.png"
- $pie.images[:basket].should == "http://foo.com/basket.png"
+ image ship:"http://foo.com/ship.png",
+ basket:"http://foo.com/basket.png"
+ images[:ship].should == "http://foo.com/ship.png"
+ images[:basket].should == "http://foo.com/basket.png"
end
end
describe "creates places" do
- it "can create a place without a description" do
- make_pie do
- create_places do
- ship
- end
- end
- $pie.places[:ship].should == {}
+
+ it "can create a place with extra options raises an error" do
+ lambda {
+ place ship:"this is a ship", extra_option:"this"
+ }.should raise_error
end
- it "cannot create a place if options are invalid (given as a symbol not a Hash)" do
- make_pie do
- create_places do
- result = ship :invalid
- result.should == nil
- end
- end
- $pie.places[:ship].should == nil
+ it "can create a place with a description" do
+ place ship:"this is a ship"
+ ship.should be_a(Place)
+ ship.name.should == :ship
+ ship.description.should == "this is a ship"
end
+
describe "with paths" do
before do
- make_pie do
- create_places do
- field description:"You are in a large, grassy field. You see many trees to the north and a path to the east"
- forest description:"It is dark in the forest"
- cliff_top description:"The path ends at the top of a steep cliff"
- cliff_bottom description:"You walked off the cliff and fell to your death"
- end
- end
+ place field:"You are in a large, grassy field. You see many trees to the north and a path to the east"
+ place forest:"It is dark in the forest"
+ place cliff_top:"The path ends at the top of a steep cliff"
+ place cliff_bottom:"You walked off the cliff and fell to your death"
end
it "should have links between two places" do
- more_pie do
- map do
- puts "----- inside map block ---"
- path(field:"North", forest:"South")
- path(field:"East", cliff_top:"West")
- end
- place = places[:field]
- place.links.should == {forest:"North", cliff_top:"East"}
-
- end
+ field.path forest:north
+ field.paths.should == {forest:north}
+ forest.paths.should == {field:south}
end
it "should have one way links" do
- more_pie do
- map do
- path(cliff_top:"East", cliff_bottom:NO_WAY_BACK)
- end
- cliff_top = places[:cliff_top]
- cliff_top.should_not == nil
- cliff_top.links.should == { cliff_bottom:"East"}
- cliff_bottom = places[:cliff_bottom]
- cliff_bottom.should_not == nil
- cliff_bottom.links.should == {}
- end
+ cliff_top.path cliff_bottom:east!
+ cliff_top.paths.should == {cliff_bottom:east}
+ cliff_bottom.paths.should == {}
end
end
end
- describe "can access places" do
- before do
- make_pie do
- create_places do
- ship description:"ookina fune"
- building description:"ookina biru"
- tower description:"ookina towa"
- end
- end
- end
-
- it "which are accessible by named key (symbol)" do
- ship = $pie.places[:ship]
- ship.should_not be_nil
- ship[:description].should == "ookina fune"
- end
-
- it "which are accessible by named key (string)" do
- ship = $pie.places["ship"]
- ship.should_not be_nil
- ship[:description].should == "ookina fune"
- end
-
- it "resulting in 2 places" do
- $pie.places.length.should == 3
- end
-
- it "and can find place after named place" do
- building = $pie.places.after(:ship)
- building.should_not be_nil
- building[:description].should == "ookina biru"
- end
-
- it "and finds nil after last place" do
- nothing = $pie.places.after(:tower)
- nothing.should be_nil
- end
-
- it "and can find place before named place" do
- building = $pie.places.before(:tower)
- building.should_not be_nil
- building[:description].should == "ookina biru"
- end
-
- it "and finds nil before first place" do
- nothing = $pie.places.before(:ship)
- nothing.should be_nil
- end
- end
+ # describe "can access places" do
+ # before do
+ # ship description:"ookina fune"
+ # building description:"ookina biru"
+ # tower description:"ookina towa"
+ # end
+ #
+ # it "which are accessible by named key (symbol)" do
+ # ship = $pie.places[:ship]
+ # ship.should_not be_nil
+ # ship[:description].should == "ookina fune"
+ # end
+ #
+ # it "which are accessible by named key (string)" do
+ # ship = $pie.places["ship"]
+ # ship.should_not be_nil
+ # ship[:description].should == "ookina fune"
+ # end
+ #
+ # it "resulting in 2 places" do
+ # $pie.places.length.should == 3
+ # end
+ #
+ # it "and can find place after named place" do
+ # building = $pie.places.after(:ship)
+ # building.should_not be_nil
+ # building[:description].should == "ookina biru"
+ # end
+ #
+ # it "and finds nil after last place" do
+ # nothing = $pie.places.after(:tower)
+ # nothing.should be_nil
+ # end
+ #
+ # it "and can find place before named place" do
+ # building = $pie.places.before(:tower)
+ # building.should_not be_nil
+ # building[:description].should == "ookina biru"
+ # end
+ #
+ # it "and finds nil before first place" do
+ # nothing = $pie.places.before(:ship)
+ # nothing.should be_nil
+ # end
+ # end
end
diff --git a/views/game_screen.erb b/views/game_screen.erb
index a5dd401..5438105 100644
--- a/views/game_screen.erb
+++ b/views/game_screen.erb
@@ -1,67 +1,69 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title><%= $current %></title>
<style type="text/css" media="screen">
body {
background: #000;
}
div#background {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%
}
div#background img {
/* Set up proportionate scaling */
width: auto;
height: 100%;
/* Set up positioning */
margin-left: auto;
margin-right: auto;
display: block;
}
div#content {
/* This is the only important rule */
/* We need our content to show up on top of the background */
position: relative;
/* These have no effect on the functionality */
width: 400px;
margin: 0 auto;
background: #fff;
padding: 20px;
font-family: helvetica, arial, sans-serif;
font-size: 12pt;
line-height: 14pt;
-moz-box-shadow: #000 4px 4px 10px;
-webkit-box-shadow: #000 4px 4px 10px;
}
</style>
</head>
<body>
<div id="background">
- <img src="<%= $pie.current_image %>" />
+ <% if current_image %>
+ <img src="<%= current_image %>" />
+ <% end %>
</div>
<div id="content">
- <p><%= $pie.current_description %></p>
+ <p><%= current_place.description %></p>
<p>
- <% $pie.places[$current].links.each do |place_name, label| %>
- <%= " <a href='#{place_name}'>#{label.to_s}</a> " %>
+ <% current_place.paths.each do |place_name, label| %>
+ <%= " <a href='#{place_name}'>#{label}</a> " %>
<% end %>
</p>
</div>
</body>
</html>
|
blazingcloud/pie
|
01671dd86a008e8a22a7123596135182178f5765
|
ok, now it is close to desired behavior
|
diff --git a/views/game_screen.erb b/views/game_screen.erb
index bf35674..a5dd401 100644
--- a/views/game_screen.erb
+++ b/views/game_screen.erb
@@ -1,58 +1,67 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title><%= $current %></title>
<style type="text/css" media="screen">
body {
background: #000;
}
+
+ div#background {
+ position: fixed;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%
+ }
- img.bg {
+ div#background img {
/* Set up proportionate scaling */
width: auto;
height: 100%;
/* Set up positioning */
- position: fixed;
margin-left: auto;
margin-right: auto;
display: block;
}
div#content {
/* This is the only important rule */
/* We need our content to show up on top of the background */
position: relative;
/* These have no effect on the functionality */
- width: 80%;
+ width: 400px;
margin: 0 auto;
background: #fff;
padding: 20px;
font-family: helvetica, arial, sans-serif;
font-size: 12pt;
line-height: 14pt;
-moz-box-shadow: #000 4px 4px 10px;
-webkit-box-shadow: #000 4px 4px 10px;
}
</style>
</head>
<body>
-<img src="<%= $pie.current_image %>" class="bg" />
+<div id="background">
+ <img src="<%= $pie.current_image %>" />
+</div>
<div id="content">
<p><%= $pie.current_description %></p>
<p>
<% $pie.places[$current].links.each do |place_name, label| %>
<%= " <a href='#{place_name}'>#{label.to_s}</a> " %>
<% end %>
</p>
</div>
</body>
</html>
|
blazingcloud/pie
|
df8a3c2318e1c39cbba8d2be841e61c0b42cd85a
|
progress on game screen with diff layout
|
diff --git a/views/full_screen.erb b/views/full_screen.erb
new file mode 100644
index 0000000..9412542
--- /dev/null
+++ b/views/full_screen.erb
@@ -0,0 +1,63 @@
+<!DOCTYPE html>
+
+<html lang="en">
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
+ <title><%= $current %></title>
+ <style type="text/css" media="screen">
+
+
+ img.bg {
+ /* Set rules to fill background */
+ min-height: 100%;
+ min-width: 1024px;
+
+ /* Set up proportionate scaling */
+ width: 100%;
+ height: auto;
+
+ /* Set up positioning */
+ position: fixed;
+ top: 0;
+ left: 0;
+ }
+
+ @media screen and (max-width: 1024px){
+ img.bg {
+ left: 50%;
+ margin-left: -512px; }
+ }
+
+ div#content {
+ /* This is the only important rule */
+ /* We need our content to show up on top of the background */
+ position: relative;
+
+ /* These have no effect on the functionality */
+ width: 80%;
+ margin: 0 auto;
+ background: #fff;
+ padding: 20px;
+ font-family: helvetica, arial, sans-serif;
+ font-size: 12pt;
+ line-height: 14pt;
+ -moz-box-shadow: #000 4px 4px 10px;
+ -webkit-box-shadow: #000 4px 4px 10px;
+ }
+
+ </style>
+</head>
+
+<body>
+<img src="<%= $pie.current_image %>" class="bg" />
+<div id="content">
+ <p><%= $pie.current_description %></p>
+ <p>
+ <% $pie.places[$current].links.each do |place_name, label| %>
+ <%= " <a href='#{place_name}'>#{label.to_s}</a> " %>
+ <% end %>
+ </p>
+</div>
+</body>
+
+</html>
diff --git a/views/game_screen.erb b/views/game_screen.erb
index 9412542..bf35674 100644
--- a/views/game_screen.erb
+++ b/views/game_screen.erb
@@ -1,63 +1,58 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title><%= $current %></title>
<style type="text/css" media="screen">
-
+ body {
+ background: #000;
+ }
+
img.bg {
- /* Set rules to fill background */
- min-height: 100%;
- min-width: 1024px;
-
+
/* Set up proportionate scaling */
- width: 100%;
- height: auto;
+ width: auto;
+ height: 100%;
/* Set up positioning */
position: fixed;
- top: 0;
- left: 0;
- }
-
- @media screen and (max-width: 1024px){
- img.bg {
- left: 50%;
- margin-left: -512px; }
- }
+ margin-left: auto;
+ margin-right: auto;
+ display: block;
+ }
div#content {
/* This is the only important rule */
/* We need our content to show up on top of the background */
position: relative;
/* These have no effect on the functionality */
width: 80%;
margin: 0 auto;
background: #fff;
padding: 20px;
font-family: helvetica, arial, sans-serif;
font-size: 12pt;
line-height: 14pt;
-moz-box-shadow: #000 4px 4px 10px;
-webkit-box-shadow: #000 4px 4px 10px;
}
</style>
</head>
<body>
<img src="<%= $pie.current_image %>" class="bg" />
<div id="content">
<p><%= $pie.current_description %></p>
<p>
<% $pie.places[$current].links.each do |place_name, label| %>
<%= " <a href='#{place_name}'>#{label.to_s}</a> " %>
<% end %>
</p>
</div>
</body>
</html>
|
blazingcloud/pie
|
b53508209fc3e5fdc9b06fa70bec550d19313b31
|
a bit more natural Japanese
|
diff --git a/book.rb b/book.rb
index 5283c03..3e9a089 100644
--- a/book.rb
+++ b/book.rb
@@ -1,17 +1,17 @@
#encoding:UTF-8
$LOAD_PATH << File.dirname(__FILE__)
require 'lib/pie'
make_pie do
create_places do
ship description:"大ããªè¹"
building description:"ookina biru"
- tower description:"ookina towa"
+ tower description:"ookina tawaa"
end
image ship:"images/big_ship.jpg",
building:"images/building.jpg",
tower:"images/tokyo_tower.jpg"
end
|
blazingcloud/pie
|
d414f2def24bf225dc3dce8cf8773f024fc8ceff
|
added some paths to spec, passing
|
diff --git a/game.rb b/game.rb
index 2e24dcb..7503a4b 100644
--- a/game.rb
+++ b/game.rb
@@ -1,17 +1,23 @@
$LOAD_PATH << File.dirname(__FILE__)
require 'lib/pie'
make_pie do
template :game_screen
create_places do
- park description:"You are in a park. You see trees to the north and a path to the east", links:{trees:"North", river_edge:"East"}
- trees description:"You are in a Japanese garden.", links:{park:"South"}
- river_edge description:"The path ends at a river", links:{in_the_river:"East", park:"West"}
+ park description:"You are in a park. You see trees to the north and a path to the east"
+ trees description:"You are in a Japanese garden."
+ river_edge description:"The path ends at a river"
in_the_river description:"You walk into the river and down"
end
+ map do
+ path {park:"North", trees:"South"}
+ path {park:"East", river_edge:"West"}
+ path {river_edge:"East", in_the_river:NO_WAY_BACK}
+ end
+
image park:"images/park.JPG"
image river_edge:"images/water.JPG"
image trees:"images/trees.JPG"
end
diff --git a/lib/pie.rb b/lib/pie.rb
index a652935..ff31582 100644
--- a/lib/pie.rb
+++ b/lib/pie.rb
@@ -1,112 +1,159 @@
require 'sinatra/base'
-
+#puts "----------------- Ruby version = #{RUBY_VERSION}"
+#raise ScriptError, "Pie requires Ruby 1.9 or higher" if RUBY_VERSION < "1.9.0"
+NO_WAY_BACK = ""
class Pie
+
+
attr_accessor :places
attr_accessor :images
attr_accessor :default_template
def initialize
@default_template = :image_page
+ @places = Places.new
+ @map = Map.new(@places)
end
class WebApp < Sinatra::Base
set :root, File.join(File.expand_path(File.dirname(__FILE__)), "..")
get '/' do
"hello"
end
get '/:place_name' do
name = params[:place_name].to_sym
$current = name unless name.nil?
puts "current place name is #{$current}"
puts "current place is #{$pie.places[$current]}"
puts "current links are #{$pie.places[$current].links.inspect}"
puts "displaying template: #{$pie.default_template.inspect}"
erb $pie.default_template
end
end
at_exit { WebApp.run! if !$0.include?("spec")}
+ class Map
+
+ def initialize places
+ @places = places
+ end
+
+ def path endpoints
+ puts "---> path #{endpoints.inspect}"
+ puts @places.inspect
+ #if h.size != 2
+ # return puts "path must have two and only two endpoints."
+ #end
+ start_place_key, end_place_key = endpoints.keys
+ label_for_end, label_for_start = endpoints.values
+
+ start_place = @places[start_place_key]
+ end_place = @places[end_place_key]
+ raise ArgumentError, "there is no place named '#{start_place_key}'" if start_place.nil?
+ raise ArgumentError, "there is no place named '#{end_place_key}'" if end_place.nil?
+
+ start_place[:links][end_place_key] = label_for_end unless label_for_end.empty?
+ end_place[:links][start_place_key] = label_for_start unless label_for_start.empty?
+ end
+ end
+
class Place < Hash
+ def initialize
+ self[:links] = {}
+ end
def links
result = self[:links]
- result ||= {}
end
end
+
class Places < Hash
def method_missing name, options = {}
unless options.is_a? Hash
puts "options for creating a place must have key and value"
return
end
puts "making a #{name} with #{options.inspect}"
place = Place.new
place.merge! options
self[name.to_sym] = place
end
def [] string_or_symbol
super string_or_symbol.to_sym
end
def after(place_name)
index = keys.index(place_name.to_sym)
next_place_name = keys[index + 1]
self[next_place_name] unless next_place_name.nil?
end
def before(place_name)
index = keys.index(place_name.to_sym)
index = index - 1
if index < 0
nil
else
prev_place_name = keys[index]
self[prev_place_name]
end
end
end
def template(template_name)
puts "--> set default template #{template_name.to_sym}"
@default_template = template_name.to_sym
end
def create_places(&block)
- @places ||= Places.new
@places.instance_eval(&block)
end
+ def map(&block)
+ puts "-------- creating map --------"
+ @map.instance_eval(&block)
+ end
+
def image(image_hash)
@images ||= {}
puts "--- set image"
puts image_hash.inspect
@images.merge!(image_hash)
end
def current_image
puts "------- current_image"
puts $current.inspect
puts @images.inspect
@images[$current.to_sym]
end
def current_description
puts "------- current_description"
puts $current.inspect
place = @places[$current.to_sym]
puts @place.inspect
place[:description] unless place.nil?
end
end
def make_pie(&block)
puts "-------------------------- making pie ---------------------------- "
$pie = Pie.new
$pie.instance_eval(&block)
puts "-------------------------- pie complete ---------------------------- "
end
+def more_pie(&block)
+ puts "-------------------------- more pie ---------------------------- "
+ if $pie.nil?
+ puts "How can you make more pie when you haven't made any pie yet?"
+ return
+ end
+ $pie.instance_eval(&block)
+ puts "-------------------------- pie complete ---------------------------- "
+end
diff --git a/spec/pie_spec.rb b/spec/pie_spec.rb
index 33d4ba8..8f70f34 100644
--- a/spec/pie_spec.rb
+++ b/spec/pie_spec.rb
@@ -1,129 +1,150 @@
require File.join(File.expand_path(File.dirname(__FILE__)), "..", "lib", "pie")
describe "making pie" do
describe "with template" do
it "has a default template" do
make_pie {}
$pie.default_template.should == :image_page
end
it "can set an alternate template" do
make_pie do
template :foo
end
$pie.default_template.should == :foo
end
end
describe "image declaration" do
it "can declare an image" do
make_pie do
image ship:"http://foo.com/ship.png"
end
$pie.images[:ship].should == "http://foo.com/ship.png"
end
it "can declare multiple image statements" do
make_pie do
image ship:"http://foo.com/ship.png"
image basket:"http://foo.com/basket.png"
end
$pie.images[:ship].should == "http://foo.com/ship.png"
$pie.images[:basket].should == "http://foo.com/basket.png"
end
it "can declare multiple images with one statement" do
make_pie do
image ship:"http://foo.com/ship.png",
- basket:"http://foo.com/basket.png"
+ basket:"http://foo.com/basket.png"
end
$pie.images[:ship].should == "http://foo.com/ship.png"
$pie.images[:basket].should == "http://foo.com/basket.png"
end
end
describe "creates places" do
it "can create a place without a description" do
make_pie do
create_places do
ship
end
end
$pie.places[:ship].should == {}
end
it "cannot create a place if options are invalid (given as a symbol not a Hash)" do
make_pie do
create_places do
result = ship :invalid
result.should == nil
end
end
$pie.places[:ship].should == nil
end
- describe "with non-linear connections" do
+ describe "with paths" do
before do
make_pie do
create_places do
- field description:"You are in a large, grassy field. You see many trees to the north and a path to the east", links:{forest:"North", cliff:"East"}
- forest description:"It is dark in the forest", links:{field:"South"}
- cliff_top description:"The path ends at the top of a steep cliff", links:{cliff_bottom:"East", field:"West"}
+ field description:"You are in a large, grassy field. You see many trees to the north and a path to the east"
+ forest description:"It is dark in the forest"
+ cliff_top description:"The path ends at the top of a steep cliff"
cliff_bottom description:"You walked off the cliff and fell to your death"
end
end
end
- it "can provide a list of places to go" do
- place = $pie.places[:field]
- place.links.should == {forest:"North", cliff:"East"}
+ it "should have links between two places" do
+ more_pie do
+ map do
+ puts "----- inside map block ---"
+ path(field:"North", forest:"South")
+ path(field:"East", cliff_top:"West")
+ end
+ place = places[:field]
+ place.links.should == {forest:"North", cliff_top:"East"}
+
+ end
+ end
+ it "should have one way links" do
+ more_pie do
+ map do
+ path(cliff_top:"East", cliff_bottom:NO_WAY_BACK)
+ end
+ cliff_top = places[:cliff_top]
+ cliff_top.should_not == nil
+ cliff_top.links.should == { cliff_bottom:"East"}
+ cliff_bottom = places[:cliff_bottom]
+ cliff_bottom.should_not == nil
+ cliff_bottom.links.should == {}
+ end
end
end
end
describe "can access places" do
before do
make_pie do
create_places do
ship description:"ookina fune"
building description:"ookina biru"
tower description:"ookina towa"
end
end
end
it "which are accessible by named key (symbol)" do
ship = $pie.places[:ship]
ship.should_not be_nil
ship[:description].should == "ookina fune"
end
it "which are accessible by named key (string)" do
ship = $pie.places["ship"]
ship.should_not be_nil
ship[:description].should == "ookina fune"
end
it "resulting in 2 places" do
$pie.places.length.should == 3
end
it "and can find place after named place" do
building = $pie.places.after(:ship)
building.should_not be_nil
building[:description].should == "ookina biru"
end
it "and finds nil after last place" do
nothing = $pie.places.after(:tower)
nothing.should be_nil
end
it "and can find place before named place" do
building = $pie.places.before(:tower)
building.should_not be_nil
building[:description].should == "ookina biru"
end
it "and finds nil before first place" do
nothing = $pie.places.before(:ship)
nothing.should be_nil
end
end
end
diff --git a/syntax_ideas.txt b/syntax_ideas.txt
index aa3f718..24170ae 100644
--- a/syntax_ideas.txt
+++ b/syntax_ideas.txt
@@ -1,88 +1,106 @@
# Draft 1
create_places do
cave description:"You are in a big cave", connects_to: { forest:"Go out"}
forest description:"The forest is very dark", connects_to: { cave:"North", cliff:"East"}
cliff description:"There is a sheer cliff that is too steep to climb", connects_to: { forest:"East"}
end
create_player do
evolve [egg:forest, rabbit:cave, smurf, wizard, warrior]
end
images {
cave:"http://flickr.com/trees.jpg",
forest:"http://flickr.com/forest.jpg",
cliff:"http://flickr.com/something.jpg",
egg:"http://flickr.com/egg.jpg",
rabbit:"http://ultrasaurus.com/photos/rabbit.png"
...
}
start forest
# Draft 2 -- implicit next/prev, images with nicer syntax (or maybe not)
create_places do
ship description:"ookina funa"
building description:"ookina biru"
tower description:"ookina towa"
end
image ship:"http://flickr.com/trees.jpg",
building:"http://flickr.com/forest.jpg",
tower:"http://flickr.com/something.jpg",
sounds {
ship:"ookina-foona.wav",
building:"biru.wav",
tower:"towa.wav"
}
# First implementation
make_pie do
create_places do
ship description:"大ããªè¹"
building description:"ookina biru"
tower description:"ookina towa"
end
image ship:"images/big_ship.jpg",
building:"images/building.jpg",
tower:"images/tokyo_tower.jpg"
end
make_pie do
template :game_screen
create_places do
park description:"You are in a park. You see trees to the north and a path to the east", links:{trees:"North", river_edge:"East"}
trees description:"You are in a Japanese garden.", links:{park:"South"}
river_edge description:"The path ends at a river", links:{in_the_river:"East", park:"West"}
in_the_river description:"You walk into the river and down"
end
image park:"images/park.JPG"
image river_edge:"images/water.JPG"
image trees:"images/trees.JPG"
end
+# Need to write code to report nicer errors
+# method_missing makes for weird errors
+
+ it "cannot create a place if options are invalid (given as a symbol not a Hash)" do
+ make_pie do
+ create_places do
+ result = ship :invalid
+ result.should == nil
+ end
+ end
+ $pie.places[:ship].should == nil
+ end
+
+ def method_missing name, options = {}
+ unless options.is_a? Hash
+ puts "options for creating a place must have key and value"
+ return
+ end
# Issues:
* image syntax is sensitive to space and this won't work:
image park :"images/park.JPG"
* creating two-way connections, which are common is cumbersome
* want to keep game logic in one place and as concise as possible
Solution:
map do
path {cave:"go into the forest", forest:"enter tunnel"}
path {cave:"step into hole", hole:no_way_back}
end
|
blazingcloud/pie
|
02f89504a7a4e3cd7c719512ca71f9737cc9c829
|
track history of pie syntax
|
diff --git a/syntax_ideas.txt b/syntax_ideas.txt
new file mode 100644
index 0000000..aa3f718
--- /dev/null
+++ b/syntax_ideas.txt
@@ -0,0 +1,88 @@
+# Draft 1
+
+create_places do
+ cave description:"You are in a big cave", connects_to: { forest:"Go out"}
+ forest description:"The forest is very dark", connects_to: { cave:"North", cliff:"East"}
+ cliff description:"There is a sheer cliff that is too steep to climb", connects_to: { forest:"East"}
+end
+
+create_player do
+ evolve [egg:forest, rabbit:cave, smurf, wizard, warrior]
+end
+
+images {
+ cave:"http://flickr.com/trees.jpg",
+ forest:"http://flickr.com/forest.jpg",
+ cliff:"http://flickr.com/something.jpg",
+ egg:"http://flickr.com/egg.jpg",
+ rabbit:"http://ultrasaurus.com/photos/rabbit.png"
+ ...
+}
+
+start forest
+
+
+# Draft 2 -- implicit next/prev, images with nicer syntax (or maybe not)
+
+create_places do
+ ship description:"ookina funa"
+ building description:"ookina biru"
+ tower description:"ookina towa"
+end
+
+image ship:"http://flickr.com/trees.jpg",
+ building:"http://flickr.com/forest.jpg",
+ tower:"http://flickr.com/something.jpg",
+
+sounds {
+ ship:"ookina-foona.wav",
+ building:"biru.wav",
+ tower:"towa.wav"
+}
+
+# First implementation
+
+make_pie do
+ create_places do
+ ship description:"大ããªè¹"
+ building description:"ookina biru"
+ tower description:"ookina towa"
+ end
+
+ image ship:"images/big_ship.jpg",
+ building:"images/building.jpg",
+ tower:"images/tokyo_tower.jpg"
+end
+
+make_pie do
+ template :game_screen
+
+ create_places do
+ park description:"You are in a park. You see trees to the north and a path to the east", links:{trees:"North", river_edge:"East"}
+ trees description:"You are in a Japanese garden.", links:{park:"South"}
+ river_edge description:"The path ends at a river", links:{in_the_river:"East", park:"West"}
+ in_the_river description:"You walk into the river and down"
+ end
+
+ image park:"images/park.JPG"
+ image river_edge:"images/water.JPG"
+ image trees:"images/trees.JPG"
+end
+
+
+# Issues:
+* image syntax is sensitive to space and this won't work:
+ image park :"images/park.JPG"
+* creating two-way connections, which are common is cumbersome
+* want to keep game logic in one place and as concise as possible
+
+Solution:
+
+map do
+ path {cave:"go into the forest", forest:"enter tunnel"}
+ path {cave:"step into hole", hole:no_way_back}
+end
+
+
+
+
|
blazingcloud/pie
|
0f4e16360ff3b86e9e3fdbb66a44b874d8a0f857
|
visual improvements to game template
|
diff --git a/views/game_screen.erb b/views/game_screen.erb
index dc24b95..9412542 100644
--- a/views/game_screen.erb
+++ b/views/game_screen.erb
@@ -1,62 +1,63 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title><%= $current %></title>
<style type="text/css" media="screen">
img.bg {
/* Set rules to fill background */
min-height: 100%;
min-width: 1024px;
/* Set up proportionate scaling */
width: 100%;
height: auto;
/* Set up positioning */
position: fixed;
top: 0;
left: 0;
}
@media screen and (max-width: 1024px){
img.bg {
left: 50%;
margin-left: -512px; }
}
div#content {
/* This is the only important rule */
/* We need our content to show up on top of the background */
position: relative;
/* These have no effect on the functionality */
- width: 100%;
+ width: 80%;
margin: 0 auto;
+ background: #fff;
padding: 20px;
font-family: helvetica, arial, sans-serif;
- font-size: 32pt;
- line-height: 40pt;
- text-align: center;
- text-shadow: 1px 1px #fff;
- }
+ font-size: 12pt;
+ line-height: 14pt;
+ -moz-box-shadow: #000 4px 4px 10px;
+ -webkit-box-shadow: #000 4px 4px 10px;
+ }
</style>
</head>
<body>
<img src="<%= $pie.current_image %>" class="bg" />
<div id="content">
<p><%= $pie.current_description %></p>
<p>
<% $pie.places[$current].links.each do |place_name, label| %>
<%= " <a href='#{place_name}'>#{label.to_s}</a> " %>
<% end %>
</p>
</div>
</body>
</html>
|
blazingcloud/pie
|
cef30cf78ab324b1093efa6992ece99c2f03ac68
|
places can now have links, see game.rb for example
|
diff --git a/book.rb b/book.rb
index a026e35..5283c03 100644
--- a/book.rb
+++ b/book.rb
@@ -1,22 +1,17 @@
#encoding:UTF-8
$LOAD_PATH << File.dirname(__FILE__)
require 'lib/pie'
-def make_pie(&block)
- $pie = Pie.new
- $pie.instance_eval(&block)
-end
-
make_pie do
create_places do
ship description:"大ããªè¹"
building description:"ookina biru"
tower description:"ookina towa"
end
image ship:"images/big_ship.jpg",
building:"images/building.jpg",
tower:"images/tokyo_tower.jpg"
end
diff --git a/game.rb b/game.rb
new file mode 100644
index 0000000..2e24dcb
--- /dev/null
+++ b/game.rb
@@ -0,0 +1,17 @@
+$LOAD_PATH << File.dirname(__FILE__)
+require 'lib/pie'
+
+make_pie do
+ template :game_screen
+
+ create_places do
+ park description:"You are in a park. You see trees to the north and a path to the east", links:{trees:"North", river_edge:"East"}
+ trees description:"You are in a Japanese garden.", links:{park:"South"}
+ river_edge description:"The path ends at a river", links:{in_the_river:"East", park:"West"}
+ in_the_river description:"You walk into the river and down"
+ end
+
+ image park:"images/park.JPG"
+ image river_edge:"images/water.JPG"
+ image trees:"images/trees.JPG"
+end
diff --git a/lib/pie.rb b/lib/pie.rb
index 1c2c0ee..a652935 100644
--- a/lib/pie.rb
+++ b/lib/pie.rb
@@ -1,94 +1,112 @@
require 'sinatra/base'
class Pie
+ attr_accessor :places
+ attr_accessor :images
+ attr_accessor :default_template
+
+ def initialize
+ @default_template = :image_page
+ end
+
class WebApp < Sinatra::Base
set :root, File.join(File.expand_path(File.dirname(__FILE__)), "..")
get '/' do
"hello"
end
get '/:place_name' do
- name = params[:place_name]
+ name = params[:place_name].to_sym
$current = name unless name.nil?
- erb :image_page
+ puts "current place name is #{$current}"
+ puts "current place is #{$pie.places[$current]}"
+ puts "current links are #{$pie.places[$current].links.inspect}"
+ puts "displaying template: #{$pie.default_template.inspect}"
+ erb $pie.default_template
end
end
at_exit { WebApp.run! if !$0.include?("spec")}
- attr_accessor :places
- attr_accessor :images
+ class Place < Hash
+ def links
+ result = self[:links]
+ result ||= {}
+ end
+ end
class Places < Hash
def method_missing name, options = {}
unless options.is_a? Hash
puts "options for creating a place must have key and value"
return
end
puts "making a #{name} with #{options.inspect}"
- self[name.to_sym] = options
+ place = Place.new
+ place.merge! options
+ self[name.to_sym] = place
+ end
+
+ def [] string_or_symbol
+ super string_or_symbol.to_sym
end
def after(place_name)
index = keys.index(place_name.to_sym)
next_place_name = keys[index + 1]
- self[next_place_name]
+ self[next_place_name] unless next_place_name.nil?
end
def before(place_name)
index = keys.index(place_name.to_sym)
index = index - 1
if index < 0
nil
else
prev_place_name = keys[index]
self[prev_place_name]
end
end
end
+ def template(template_name)
+ puts "--> set default template #{template_name.to_sym}"
+ @default_template = template_name.to_sym
+ end
+
def create_places(&block)
@places ||= Places.new
@places.instance_eval(&block)
end
def image(image_hash)
@images ||= {}
puts "--- set image"
puts image_hash.inspect
@images.merge!(image_hash)
end
def current_image
puts "------- current_image"
puts $current.inspect
puts @images.inspect
@images[$current.to_sym]
end
def current_description
puts "------- current_description"
puts $current.inspect
- puts @places.inspect
place = @places[$current.to_sym]
+ puts @place.inspect
place[:description] unless place.nil?
end
end
def make_pie(&block)
+ puts "-------------------------- making pie ---------------------------- "
$pie = Pie.new
$pie.instance_eval(&block)
+ puts "-------------------------- pie complete ---------------------------- "
end
-make_pie do
- create_places do
- ship description:"ookina funa"
- building description:"ookina biru"
- tower description:"ookina towa"
- end
-
- image ship:"images/big_ship.jpg",
- building:"images/building.jpg",
- tower:"images/tokyo_tower.jpg"
-end
diff --git a/spec/pie_spec.rb b/spec/pie_spec.rb
index ef0d101..33d4ba8 100644
--- a/spec/pie_spec.rb
+++ b/spec/pie_spec.rb
@@ -1,95 +1,129 @@
-require File.join(File.expand_path(File.dirname(__FILE__)), "pie")
+require File.join(File.expand_path(File.dirname(__FILE__)), "..", "lib", "pie")
describe "making pie" do
+ describe "with template" do
+ it "has a default template" do
+ make_pie {}
+ $pie.default_template.should == :image_page
+ end
+ it "can set an alternate template" do
+ make_pie do
+ template :foo
+ end
+ $pie.default_template.should == :foo
+ end
+ end
describe "image declaration" do
it "can declare an image" do
make_pie do
image ship:"http://foo.com/ship.png"
end
$pie.images[:ship].should == "http://foo.com/ship.png"
end
it "can declare multiple image statements" do
make_pie do
image ship:"http://foo.com/ship.png"
image basket:"http://foo.com/basket.png"
end
$pie.images[:ship].should == "http://foo.com/ship.png"
$pie.images[:basket].should == "http://foo.com/basket.png"
end
it "can declare multiple images with one statement" do
make_pie do
image ship:"http://foo.com/ship.png",
basket:"http://foo.com/basket.png"
end
$pie.images[:ship].should == "http://foo.com/ship.png"
$pie.images[:basket].should == "http://foo.com/basket.png"
end
end
describe "creates places" do
it "can create a place without a description" do
make_pie do
create_places do
ship
end
end
$pie.places[:ship].should == {}
end
it "cannot create a place if options are invalid (given as a symbol not a Hash)" do
make_pie do
create_places do
result = ship :invalid
result.should == nil
end
end
$pie.places[:ship].should == nil
end
+ describe "with non-linear connections" do
+ before do
+ make_pie do
+ create_places do
+ field description:"You are in a large, grassy field. You see many trees to the north and a path to the east", links:{forest:"North", cliff:"East"}
+ forest description:"It is dark in the forest", links:{field:"South"}
+ cliff_top description:"The path ends at the top of a steep cliff", links:{cliff_bottom:"East", field:"West"}
+ cliff_bottom description:"You walked off the cliff and fell to your death"
+ end
+ end
+ end
+ it "can provide a list of places to go" do
+ place = $pie.places[:field]
+ place.links.should == {forest:"North", cliff:"East"}
+ end
+ end
end
describe "can access places" do
before do
make_pie do
create_places do
ship description:"ookina fune"
building description:"ookina biru"
tower description:"ookina towa"
end
end
end
- it "which are accessible by named key" do
+ it "which are accessible by named key (symbol)" do
ship = $pie.places[:ship]
ship.should_not be_nil
ship[:description].should == "ookina fune"
end
+
+ it "which are accessible by named key (string)" do
+ ship = $pie.places["ship"]
+ ship.should_not be_nil
+ ship[:description].should == "ookina fune"
+ end
it "resulting in 2 places" do
$pie.places.length.should == 3
end
it "and can find place after named place" do
building = $pie.places.after(:ship)
building.should_not be_nil
building[:description].should == "ookina biru"
end
it "and finds nil after last place" do
nothing = $pie.places.after(:tower)
nothing.should be_nil
end
it "and can find place before named place" do
building = $pie.places.before(:tower)
building.should_not be_nil
building[:description].should == "ookina biru"
end
it "and finds nil before first place" do
nothing = $pie.places.before(:ship)
nothing.should be_nil
end
end
end
diff --git a/views/game_screen.erb b/views/game_screen.erb
new file mode 100644
index 0000000..dc24b95
--- /dev/null
+++ b/views/game_screen.erb
@@ -0,0 +1,62 @@
+<!DOCTYPE html>
+
+<html lang="en">
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
+ <title><%= $current %></title>
+ <style type="text/css" media="screen">
+
+
+ img.bg {
+ /* Set rules to fill background */
+ min-height: 100%;
+ min-width: 1024px;
+
+ /* Set up proportionate scaling */
+ width: 100%;
+ height: auto;
+
+ /* Set up positioning */
+ position: fixed;
+ top: 0;
+ left: 0;
+ }
+
+ @media screen and (max-width: 1024px){
+ img.bg {
+ left: 50%;
+ margin-left: -512px; }
+ }
+
+ div#content {
+ /* This is the only important rule */
+ /* We need our content to show up on top of the background */
+ position: relative;
+
+ /* These have no effect on the functionality */
+ width: 100%;
+ margin: 0 auto;
+ padding: 20px;
+ font-family: helvetica, arial, sans-serif;
+ font-size: 32pt;
+ line-height: 40pt;
+ text-align: center;
+ text-shadow: 1px 1px #fff;
+ }
+
+ </style>
+</head>
+
+<body>
+<img src="<%= $pie.current_image %>" class="bg" />
+<div id="content">
+ <p><%= $pie.current_description %></p>
+ <p>
+ <% $pie.places[$current].links.each do |place_name, label| %>
+ <%= " <a href='#{place_name}'>#{label.to_s}</a> " %>
+ <% end %>
+ </p>
+</div>
+</body>
+
+</html>
|
blazingcloud/pie
|
d52b789219fd49450d3667be03dc2b2ac7d36e95
|
some Japanese text:
|
diff --git a/book.rb b/book.rb
index 952c6b0..a026e35 100644
--- a/book.rb
+++ b/book.rb
@@ -1,21 +1,22 @@
+#encoding:UTF-8
$LOAD_PATH << File.dirname(__FILE__)
require 'lib/pie'
def make_pie(&block)
$pie = Pie.new
$pie.instance_eval(&block)
end
make_pie do
create_places do
- ship description:"ookina fune"
+ ship description:"大ããªè¹"
building description:"ookina biru"
tower description:"ookina towa"
end
image ship:"images/big_ship.jpg",
building:"images/building.jpg",
tower:"images/tokyo_tower.jpg"
end
|
blazingcloud/pie
|
e0c5136064a74512cfd101b5ee408e557891f821
|
better path handling for require
|
diff --git a/spec/pie_spec.rb b/spec/pie_spec.rb
index 9210473..ef0d101 100644
--- a/spec/pie_spec.rb
+++ b/spec/pie_spec.rb
@@ -1,95 +1,95 @@
-require File.expand_path(File.dirname(__FILE__) + '/pie')
+require File.join(File.expand_path(File.dirname(__FILE__)), "pie")
describe "making pie" do
describe "image declaration" do
it "can declare an image" do
make_pie do
image ship:"http://foo.com/ship.png"
end
$pie.images[:ship].should == "http://foo.com/ship.png"
end
it "can declare multiple image statements" do
make_pie do
image ship:"http://foo.com/ship.png"
image basket:"http://foo.com/basket.png"
end
$pie.images[:ship].should == "http://foo.com/ship.png"
$pie.images[:basket].should == "http://foo.com/basket.png"
end
it "can declare multiple images with one statement" do
make_pie do
image ship:"http://foo.com/ship.png",
basket:"http://foo.com/basket.png"
end
$pie.images[:ship].should == "http://foo.com/ship.png"
$pie.images[:basket].should == "http://foo.com/basket.png"
end
end
describe "creates places" do
it "can create a place without a description" do
make_pie do
create_places do
ship
end
end
$pie.places[:ship].should == {}
end
it "cannot create a place if options are invalid (given as a symbol not a Hash)" do
make_pie do
create_places do
result = ship :invalid
result.should == nil
end
end
$pie.places[:ship].should == nil
end
end
describe "can access places" do
before do
make_pie do
create_places do
ship description:"ookina fune"
building description:"ookina biru"
tower description:"ookina towa"
end
end
end
it "which are accessible by named key" do
ship = $pie.places[:ship]
ship.should_not be_nil
ship[:description].should == "ookina fune"
end
it "resulting in 2 places" do
$pie.places.length.should == 3
end
it "and can find place after named place" do
building = $pie.places.after(:ship)
building.should_not be_nil
building[:description].should == "ookina biru"
end
it "and finds nil after last place" do
nothing = $pie.places.after(:tower)
nothing.should be_nil
end
it "and can find place before named place" do
building = $pie.places.before(:tower)
building.should_not be_nil
building[:description].should == "ookina biru"
end
it "and finds nil before first place" do
nothing = $pie.places.before(:ship)
nothing.should be_nil
end
end
end
|
blazingcloud/pie
|
613ab7e8265b6061e74ad3daefaf7d8d8fbe44d7
|
fixed book & added drop shadow
|
diff --git a/book.rb b/book.rb
index 870145c..952c6b0 100644
--- a/book.rb
+++ b/book.rb
@@ -1,21 +1,21 @@
$LOAD_PATH << File.dirname(__FILE__)
-require 'pie'
+require 'lib/pie'
def make_pie(&block)
$pie = Pie.new
$pie.instance_eval(&block)
end
make_pie do
create_places do
ship description:"ookina fune"
building description:"ookina biru"
tower description:"ookina towa"
end
image ship:"images/big_ship.jpg",
building:"images/building.jpg",
tower:"images/tokyo_tower.jpg"
end
diff --git a/lib/pie.rb b/lib/pie.rb
index 81c85a3..1c2c0ee 100644
--- a/lib/pie.rb
+++ b/lib/pie.rb
@@ -1,94 +1,94 @@
require 'sinatra/base'
class Pie
class WebApp < Sinatra::Base
- set :root, File.dirname(__FILE__)
+ set :root, File.join(File.expand_path(File.dirname(__FILE__)), "..")
get '/' do
"hello"
end
get '/:place_name' do
name = params[:place_name]
$current = name unless name.nil?
erb :image_page
end
end
at_exit { WebApp.run! if !$0.include?("spec")}
attr_accessor :places
attr_accessor :images
class Places < Hash
def method_missing name, options = {}
unless options.is_a? Hash
puts "options for creating a place must have key and value"
return
end
puts "making a #{name} with #{options.inspect}"
self[name.to_sym] = options
end
def after(place_name)
index = keys.index(place_name.to_sym)
next_place_name = keys[index + 1]
self[next_place_name]
end
def before(place_name)
index = keys.index(place_name.to_sym)
index = index - 1
if index < 0
nil
else
prev_place_name = keys[index]
self[prev_place_name]
end
end
end
def create_places(&block)
@places ||= Places.new
@places.instance_eval(&block)
end
def image(image_hash)
@images ||= {}
puts "--- set image"
puts image_hash.inspect
@images.merge!(image_hash)
end
def current_image
puts "------- current_image"
puts $current.inspect
puts @images.inspect
@images[$current.to_sym]
end
def current_description
puts "------- current_description"
puts $current.inspect
puts @places.inspect
place = @places[$current.to_sym]
place[:description] unless place.nil?
end
end
def make_pie(&block)
$pie = Pie.new
$pie.instance_eval(&block)
end
make_pie do
create_places do
ship description:"ookina funa"
building description:"ookina biru"
tower description:"ookina towa"
end
image ship:"images/big_ship.jpg",
building:"images/building.jpg",
tower:"images/tokyo_tower.jpg"
end
diff --git a/views/image_page.erb b/views/image_page.erb
index 7cc2c65..2464fdf 100644
--- a/views/image_page.erb
+++ b/views/image_page.erb
@@ -1,56 +1,57 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title><%= $current %></title>
<style type="text/css" media="screen">
img.bg {
/* Set rules to fill background */
min-height: 100%;
min-width: 1024px;
/* Set up proportionate scaling */
width: 100%;
height: auto;
/* Set up positioning */
position: fixed;
top: 0;
left: 0;
}
@media screen and (max-width: 1024px){
img.bg {
left: 50%;
margin-left: -512px; }
}
div#content {
/* This is the only important rule */
/* We need our content to show up on top of the background */
position: relative;
/* These have no effect on the functionality */
width: 100%;
margin: 0 auto;
padding: 20px;
font-family: helvetica, arial, sans-serif;
font-size: 32pt;
line-height: 40pt;
text-align: center;
+ text-shadow: 1px 1px #fff;
}
</style>
</head>
<body>
<img src="<%= $pie.current_image %>" class="bg" />
<div id="content">
<p><%= $pie.current_description %></p>
</div>
</body>
</html>
|
blazingcloud/pie
|
c2f9f758bdafc9fce94d65eded92aeda4924d19a
|
layout improvements
|
diff --git a/views/image_page.erb b/views/image_page.erb
index 019e54e..7cc2c65 100644
--- a/views/image_page.erb
+++ b/views/image_page.erb
@@ -1,65 +1,56 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
- <title>Full Page Background Image, Technique #2</title>
+ <title><%= $current %></title>
<style type="text/css" media="screen">
img.bg {
/* Set rules to fill background */
min-height: 100%;
min-width: 1024px;
/* Set up proportionate scaling */
width: 100%;
height: auto;
/* Set up positioning */
position: fixed;
top: 0;
left: 0;
}
@media screen and (max-width: 1024px){
img.bg {
left: 50%;
margin-left: -512px; }
}
div#content {
/* This is the only important rule */
/* We need our content to show up on top of the background */
position: relative;
-
/* These have no effect on the functionality */
- width: 500px;
+ width: 100%;
margin: 0 auto;
- background: #fff;
padding: 20px;
font-family: helvetica, arial, sans-serif;
- font-size: 10pt;
- line-height: 16pt;
- -moz-box-shadow: #000 4px 4px 10px;
- -webkit-box-shadow: #000 4px 4px 10px;
+ font-size: 32pt;
+ line-height: 40pt;
+ text-align: center;
}
- body {
- /* These rules have no effect on the functionality */
- /* They are for styling only */
- margin: 0;
- padding: 20px 0 0 0;
- }
</style>
</head>
<body>
<img src="<%= $pie.current_image %>" class="bg" />
<div id="content">
<p><%= $pie.current_description %></p>
</div>
</body>
</html>
|
blazingcloud/pie
|
4e92094aa9df22973a89263c44765007b711b109
|
Making a lib & spec directory
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..485dee6
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+.idea
diff --git a/Gemfile b/Gemfile
index 1a885bb..212d344 100644
--- a/Gemfile
+++ b/Gemfile
@@ -1,10 +1,11 @@
# A sample Gemfile
source "http://rubygems.org"
gem "sinatra"
gem "sinatra-auto-reload"
group :test do
+ gem "rspec"
gem "capybara"
gem "rack-test"
end
diff --git a/Gemfile.lock b/Gemfile.lock
index 6efae57..a8bbd29 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -1,37 +1,39 @@
GEM
remote: http://rubygems.org/
specs:
capybara (0.3.9)
culerity (>= 0.2.4)
mime-types (>= 1.16)
nokogiri (>= 1.3.3)
rack (>= 1.0.0)
rack-test (>= 0.5.4)
selenium-webdriver (>= 0.0.3)
culerity (0.2.12)
ffi (0.6.3)
rake (>= 0.8.7)
json_pure (1.4.6)
mime-types (1.16)
nokogiri (1.4.3.1)
rack (1.2.1)
rack-test (0.5.4)
rack (>= 1.0)
rake (0.8.7)
+ rspec (1.3.0)
rubyzip (0.9.4)
selenium-webdriver (0.0.28)
ffi (>= 0.6.1)
json_pure
rubyzip
sinatra (1.0)
rack (>= 1.0)
sinatra-auto-reload (0.0.6)
PLATFORMS
ruby
DEPENDENCIES
capybara
rack-test
+ rspec
sinatra
sinatra-auto-reload
diff --git a/pie.rb b/lib/pie.rb
similarity index 100%
rename from pie.rb
rename to lib/pie.rb
diff --git a/pie_app_spec.rb b/pie_app_spec.rb
deleted file mode 100644
index daaa074..0000000
--- a/pie_app_spec.rb
+++ /dev/null
@@ -1,35 +0,0 @@
-$LOAD_PATH << File.dirname(__FILE__)
-require 'pie'
-require 'capybara'
-require 'capybara/dsl'
-
-describe "app created with pie" do
- include Capybara
-
- before do
- Capybara.app = Pie::WebApp
- end
-
- it "should say hello for the root path" do
- visit '/'
- page.should have_content "hello"
- end
-
- describe "with one place and an image" do
- before do
- make_pie do
- create_places do
- ship description:"ookina fune"
- end
-
- image ship:"images/big_ship.jpg"
- end
- end
- it "should display the ship page" do
- visit '/ship'
- page.should have_content('ookina fune')
- end
- end
-
-
-end
diff --git a/spec/pie_app_spec.rb b/spec/pie_app_spec.rb
new file mode 100644
index 0000000..0619bff
--- /dev/null
+++ b/spec/pie_app_spec.rb
@@ -0,0 +1,54 @@
+$LOAD_PATH << File.join(File.expand_path(File.dirname(__FILE__)), "..", "lib")
+require 'pie'
+require 'capybara'
+require 'capybara/dsl'
+
+describe "app created with pie" do
+ include Capybara
+
+ before do
+ Capybara.app = Pie::WebApp
+ end
+
+ it "should say hello for the root path" do
+ visit '/'
+ page.should have_content "hello"
+ end
+
+ describe "with one place and an image" do
+ before do
+ puts "in before"
+ make_pie do
+ puts "in make pie"
+ create_places do
+ puts "in create places"
+ ship description:"ookina fune"
+ puts "made a ship!"
+ end
+ puts "about to add an image"
+ image ship:"images/big_ship.jpg"
+ end
+ end
+ it "should display the ship page" do
+ visit '/ship'
+ page.should have_content('ookina fune')
+ end
+ end
+
+ describe "with two places and images" do
+ before do
+ make_pie do
+ create_places do
+ ship description:"ookina fune"
+ building description:"ookina biru"
+ end
+ image ship:"images/big_ship.jpg"
+ image building:"images/building.jpg"
+ end
+ end
+ it "should display the next button" do
+ visit '/ship'
+ page.should have_content('next')
+ end
+ end
+end
diff --git a/pie_spec.rb b/spec/pie_spec.rb
similarity index 100%
rename from pie_spec.rb
rename to spec/pie_spec.rb
|
blazingcloud/pie
|
4aef7bc06911cdc97ad4f964b3a1abb785f6b20b
|
size background to full screen
|
diff --git a/views/image_page.erb b/views/image_page.erb
index 35cc795..019e54e 100644
--- a/views/image_page.erb
+++ b/views/image_page.erb
@@ -1,31 +1,65 @@
-<html>
-<head>
-<style type="text/css">
- .page {
- width: 100%;
- height: 100%;
- margin-left: auto;
- margin-right: auto;
- }
-
- img {
- margin-left: auto;
- margin-right: auto;
- width: 100%;
- height: 100%;
- }
+<!DOCTYPE html>
- .description {
- font-size: 72;
- font-weight: bold;
- text-align: center
- }
-</style>
+<html lang="en">
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
+ <title>Full Page Background Image, Technique #2</title>
+ <style type="text/css" media="screen">
+
+
+ img.bg {
+ /* Set rules to fill background */
+ min-height: 100%;
+ min-width: 1024px;
+
+ /* Set up proportionate scaling */
+ width: 100%;
+ height: auto;
+
+ /* Set up positioning */
+ position: fixed;
+ top: 0;
+ left: 0;
+ }
+
+ @media screen and (max-width: 1024px){
+ img.bg {
+ left: 50%;
+ margin-left: -512px; }
+ }
+
+ div#content {
+ /* This is the only important rule */
+ /* We need our content to show up on top of the background */
+ position: relative;
+
+
+ /* These have no effect on the functionality */
+ width: 500px;
+ margin: 0 auto;
+ background: #fff;
+ padding: 20px;
+ font-family: helvetica, arial, sans-serif;
+ font-size: 10pt;
+ line-height: 16pt;
+ -moz-box-shadow: #000 4px 4px 10px;
+ -webkit-box-shadow: #000 4px 4px 10px;
+ }
+
+ body {
+ /* These rules have no effect on the functionality */
+ /* They are for styling only */
+ margin: 0;
+ padding: 20px 0 0 0;
+ }
+ </style>
</head>
+
<body>
-<div class="page">
- <div class="description"><%= $pie.current_description %></div>
- <img src="<%= $pie.current_image %>" alt="image" />
+<img src="<%= $pie.current_image %>" class="bg" />
+<div id="content">
+ <p><%= $pie.current_description %></p>
</div>
</body>
+
</html>
|
blazingcloud/pie
|
ecf85b14627a4a356bd75eb7a19ace33357cb213
|
added spec for description and gem for auto-reload
|
diff --git a/Gemfile b/Gemfile
index 5f3d19f..1a885bb 100644
--- a/Gemfile
+++ b/Gemfile
@@ -1,9 +1,10 @@
# A sample Gemfile
source "http://rubygems.org"
gem "sinatra"
+gem "sinatra-auto-reload"
group :test do
gem "capybara"
gem "rack-test"
end
diff --git a/Gemfile.lock b/Gemfile.lock
index 95c5db4..6efae57 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -1,35 +1,37 @@
GEM
remote: http://rubygems.org/
specs:
capybara (0.3.9)
culerity (>= 0.2.4)
mime-types (>= 1.16)
nokogiri (>= 1.3.3)
rack (>= 1.0.0)
rack-test (>= 0.5.4)
selenium-webdriver (>= 0.0.3)
culerity (0.2.12)
ffi (0.6.3)
rake (>= 0.8.7)
json_pure (1.4.6)
mime-types (1.16)
nokogiri (1.4.3.1)
rack (1.2.1)
rack-test (0.5.4)
rack (>= 1.0)
rake (0.8.7)
rubyzip (0.9.4)
selenium-webdriver (0.0.28)
ffi (>= 0.6.1)
json_pure
rubyzip
sinatra (1.0)
rack (>= 1.0)
+ sinatra-auto-reload (0.0.6)
PLATFORMS
ruby
DEPENDENCIES
capybara
rack-test
sinatra
+ sinatra-auto-reload
diff --git a/pie_app_spec.rb b/pie_app_spec.rb
index 28885f3..daaa074 100644
--- a/pie_app_spec.rb
+++ b/pie_app_spec.rb
@@ -1,35 +1,35 @@
$LOAD_PATH << File.dirname(__FILE__)
require 'pie'
require 'capybara'
require 'capybara/dsl'
describe "app created with pie" do
include Capybara
before do
Capybara.app = Pie::WebApp
end
it "should say hello for the root path" do
visit '/'
page.should have_content "hello"
end
describe "with one place and an image" do
before do
make_pie do
create_places do
ship description:"ookina fune"
end
image ship:"images/big_ship.jpg"
end
end
- #it "should display the ship page" do
- # visit '/ship'
- # page.should have_content('ookina fune')
- #end
+ it "should display the ship page" do
+ visit '/ship'
+ page.should have_content('ookina fune')
+ end
end
end
diff --git a/views/image_page.erb b/views/image_page.erb
index 0803795..35cc795 100644
--- a/views/image_page.erb
+++ b/views/image_page.erb
@@ -1,31 +1,31 @@
<html>
<head>
<style type="text/css">
.page {
width: 100%;
height: 100%;
margin-left: auto;
margin-right: auto;
}
img {
margin-left: auto;
margin-right: auto;
width: 100%;
height: 100%;
}
.description {
- font-size: 36;
+ font-size: 72;
font-weight: bold;
text-align: center
}
</style>
</head>
<body>
<div class="page">
<div class="description"><%= $pie.current_description %></div>
<img src="<%= $pie.current_image %>" alt="image" />
</div>
</body>
</html>
|
blazingcloud/pie
|
687a656dedc045db990e930d63ef87fee37e884c
|
fixed app
|
diff --git a/pie.rb b/pie.rb
index 4c5af1f..81c85a3 100644
--- a/pie.rb
+++ b/pie.rb
@@ -1,94 +1,94 @@
require 'sinatra/base'
class Pie
class WebApp < Sinatra::Base
set :root, File.dirname(__FILE__)
get '/' do
"hello"
end
get '/:place_name' do
name = params[:place_name]
$current = name unless name.nil?
erb :image_page
end
end
at_exit { WebApp.run! if !$0.include?("spec")}
attr_accessor :places
attr_accessor :images
class Places < Hash
def method_missing name, options = {}
unless options.is_a? Hash
puts "options for creating a place must have key and value"
return
end
puts "making a #{name} with #{options.inspect}"
self[name.to_sym] = options
end
def after(place_name)
index = keys.index(place_name.to_sym)
next_place_name = keys[index + 1]
self[next_place_name]
end
def before(place_name)
index = keys.index(place_name.to_sym)
index = index - 1
if index < 0
nil
else
prev_place_name = keys[index]
self[prev_place_name]
end
end
end
def create_places(&block)
@places ||= Places.new
@places.instance_eval(&block)
end
def image(image_hash)
@images ||= {}
puts "--- set image"
puts image_hash.inspect
@images.merge!(image_hash)
end
def current_image
puts "------- current_image"
puts $current.inspect
puts @images.inspect
@images[$current.to_sym]
end
def current_description
puts "------- current_description"
- puts $current
- puts @places
+ puts $current.inspect
+ puts @places.inspect
place = @places[$current.to_sym]
place[:description] unless place.nil?
end
end
def make_pie(&block)
$pie = Pie.new
$pie.instance_eval(&block)
end
make_pie do
create_places do
ship description:"ookina funa"
building description:"ookina biru"
tower description:"ookina towa"
end
image ship:"images/big_ship.jpg",
building:"images/building.jpg",
tower:"images/tokyo_tower.jpg"
end
diff --git a/views/image_page.erb b/views/image_page.erb
index b734f77..0803795 100644
--- a/views/image_page.erb
+++ b/views/image_page.erb
@@ -1,30 +1,31 @@
<html>
<head>
<style type="text/css">
.page {
width: 100%;
height: 100%;
margin-left: auto;
margin-right: auto;
}
img {
margin-left: auto;
margin-right: auto;
width: 100%;
height: 100%;
}
- p {
+ .description {
font-size: 36;
font-weight: bold;
text-align: center
}
</style>
</head>
<body>
<div class="page">
+ <div class="description"><%= $pie.current_description %></div>
<img src="<%= $pie.current_image %>" alt="image" />
</div>
</body>
</html>
|
blazingcloud/pie
|
cfec77085522187fbfc1c8726c2b07320c9d6929
|
simple test with rack
|
diff --git a/pie_app_spec.rb b/pie_app_spec.rb
new file mode 100644
index 0000000..bd7a53e
--- /dev/null
+++ b/pie_app_spec.rb
@@ -0,0 +1,34 @@
+$LOAD_PATH << File.dirname(__FILE__)
+require 'pie'
+require 'rack/test'
+
+describe "app created with pie" do
+ include Rack::Test::Methods
+
+ def app
+ Pie::WebApp
+ end
+
+ it "should say hello for the root path" do
+ get '/'
+ last_response.body.should == "hello"
+ end
+
+ describe "with one place and an image" do
+ before do
+ make_pie do
+ create_places do
+ ship description:"ookina fune"
+ end
+
+ image ship:"images/big_ship.jpg"
+ end
+ end
+ #it "should display the ship page" do
+ # visit '/ship'
+ # page.should have_content('ookina fune')
+ #end
+ end
+
+
+end
|
blazingcloud/pie
|
2e2f5aaca6819e1cdcbe0fe62315e3082f26f8e8
|
adding .bundle
|
diff --git a/.bundle/config b/.bundle/config
new file mode 100644
index 0000000..8ebbe30
--- /dev/null
+++ b/.bundle/config
@@ -0,0 +1,2 @@
+---
+BUNDLE_DISABLE_SHARED_GEMS: "1"
|
blazingcloud/pie
|
83c1738fc2dd13fbaa49d63ad859e3842a394b86
|
make pie auto-run again (except when running spec)
|
diff --git a/Gemfile b/Gemfile
new file mode 100644
index 0000000..5f3d19f
--- /dev/null
+++ b/Gemfile
@@ -0,0 +1,9 @@
+# A sample Gemfile
+source "http://rubygems.org"
+
+gem "sinatra"
+
+group :test do
+ gem "capybara"
+ gem "rack-test"
+end
diff --git a/Gemfile.lock b/Gemfile.lock
new file mode 100644
index 0000000..95c5db4
--- /dev/null
+++ b/Gemfile.lock
@@ -0,0 +1,35 @@
+GEM
+ remote: http://rubygems.org/
+ specs:
+ capybara (0.3.9)
+ culerity (>= 0.2.4)
+ mime-types (>= 1.16)
+ nokogiri (>= 1.3.3)
+ rack (>= 1.0.0)
+ rack-test (>= 0.5.4)
+ selenium-webdriver (>= 0.0.3)
+ culerity (0.2.12)
+ ffi (0.6.3)
+ rake (>= 0.8.7)
+ json_pure (1.4.6)
+ mime-types (1.16)
+ nokogiri (1.4.3.1)
+ rack (1.2.1)
+ rack-test (0.5.4)
+ rack (>= 1.0)
+ rake (0.8.7)
+ rubyzip (0.9.4)
+ selenium-webdriver (0.0.28)
+ ffi (>= 0.6.1)
+ json_pure
+ rubyzip
+ sinatra (1.0)
+ rack (>= 1.0)
+
+PLATFORMS
+ ruby
+
+DEPENDENCIES
+ capybara
+ rack-test
+ sinatra
diff --git a/pie.rb b/pie.rb
index fa2e241..4c5af1f 100644
--- a/pie.rb
+++ b/pie.rb
@@ -1,94 +1,94 @@
require 'sinatra/base'
class Pie
class WebApp < Sinatra::Base
set :root, File.dirname(__FILE__)
get '/' do
"hello"
end
get '/:place_name' do
name = params[:place_name]
$current = name unless name.nil?
erb :image_page
end
end
- at_exit { WebApp.run! if $0.include?("_spec")}
+ at_exit { WebApp.run! if !$0.include?("spec")}
attr_accessor :places
attr_accessor :images
class Places < Hash
def method_missing name, options = {}
unless options.is_a? Hash
puts "options for creating a place must have key and value"
return
end
puts "making a #{name} with #{options.inspect}"
self[name.to_sym] = options
end
def after(place_name)
index = keys.index(place_name.to_sym)
next_place_name = keys[index + 1]
self[next_place_name]
end
def before(place_name)
index = keys.index(place_name.to_sym)
index = index - 1
if index < 0
nil
else
prev_place_name = keys[index]
self[prev_place_name]
end
end
end
def create_places(&block)
@places ||= Places.new
@places.instance_eval(&block)
end
def image(image_hash)
@images ||= {}
puts "--- set image"
puts image_hash.inspect
@images.merge!(image_hash)
end
def current_image
puts "------- current_image"
puts $current.inspect
puts @images.inspect
@images[$current.to_sym]
end
def current_description
puts "------- current_description"
puts $current
puts @places
place = @places[$current.to_sym]
place[:description] unless place.nil?
end
end
def make_pie(&block)
$pie = Pie.new
$pie.instance_eval(&block)
end
make_pie do
create_places do
ship description:"ookina funa"
building description:"ookina biru"
tower description:"ookina towa"
end
image ship:"images/big_ship.jpg",
building:"images/building.jpg",
tower:"images/tokyo_tower.jpg"
end
|
blazingcloud/pie
|
2a6a20f3a4ac30c89c9890cc28d747b96179cf0e
|
created after and before for accessing places, with specs
|
diff --git a/book.rb b/book.rb
index a8a5c9b..870145c 100644
--- a/book.rb
+++ b/book.rb
@@ -1,21 +1,21 @@
$LOAD_PATH << File.dirname(__FILE__)
require 'pie'
def make_pie(&block)
$pie = Pie.new
$pie.instance_eval(&block)
end
make_pie do
create_places do
- ship description:"ookina funa"
+ ship description:"ookina fune"
building description:"ookina biru"
tower description:"ookina towa"
end
image ship:"images/big_ship.jpg",
building:"images/building.jpg",
tower:"images/tokyo_tower.jpg"
end
diff --git a/pie.rb b/pie.rb
index 42abc53..fa2e241 100644
--- a/pie.rb
+++ b/pie.rb
@@ -1,73 +1,94 @@
require 'sinatra/base'
class Pie
class WebApp < Sinatra::Base
set :root, File.dirname(__FILE__)
get '/' do
"hello"
end
get '/:place_name' do
name = params[:place_name]
$current = name unless name.nil?
erb :image_page
end
end
at_exit { WebApp.run! if $0.include?("_spec")}
attr_accessor :places
attr_accessor :images
- class Places < Array
- def method_missing name, *args
- puts "making a #{name} with #{args[0].inspect}"
- self << {name.to_sym => args[0]}
+ class Places < Hash
+ def method_missing name, options = {}
+ unless options.is_a? Hash
+ puts "options for creating a place must have key and value"
+ return
+ end
+ puts "making a #{name} with #{options.inspect}"
+ self[name.to_sym] = options
+ end
+
+ def after(place_name)
+ index = keys.index(place_name.to_sym)
+ next_place_name = keys[index + 1]
+ self[next_place_name]
+ end
+
+ def before(place_name)
+ index = keys.index(place_name.to_sym)
+ index = index - 1
+ if index < 0
+ nil
+ else
+ prev_place_name = keys[index]
+ self[prev_place_name]
+ end
end
end
def create_places(&block)
@places ||= Places.new
@places.instance_eval(&block)
end
def image(image_hash)
@images ||= {}
puts "--- set image"
puts image_hash.inspect
@images.merge!(image_hash)
end
def current_image
puts "------- current_image"
puts $current.inspect
puts @images.inspect
@images[$current.to_sym]
end
def current_description
puts "------- current_description"
puts $current
puts @places
place = @places[$current.to_sym]
place[:description] unless place.nil?
end
end
def make_pie(&block)
$pie = Pie.new
$pie.instance_eval(&block)
end
make_pie do
create_places do
ship description:"ookina funa"
building description:"ookina biru"
tower description:"ookina towa"
end
image ship:"images/big_ship.jpg",
building:"images/building.jpg",
tower:"images/tokyo_tower.jpg"
end
diff --git a/pie_spec.rb b/pie_spec.rb
index c945bad..9210473 100644
--- a/pie_spec.rb
+++ b/pie_spec.rb
@@ -1,30 +1,95 @@
require File.expand_path(File.dirname(__FILE__) + '/pie')
describe "making pie" do
+ describe "image declaration" do
+ it "can declare an image" do
+ make_pie do
+ image ship:"http://foo.com/ship.png"
+ end
+ $pie.images[:ship].should == "http://foo.com/ship.png"
+ end
- it "can declare an image" do
- make_pie do
- image ship:"http://foo.com/ship.png"
+ it "can declare multiple image statements" do
+ make_pie do
+ image ship:"http://foo.com/ship.png"
+ image basket:"http://foo.com/basket.png"
+ end
+ $pie.images[:ship].should == "http://foo.com/ship.png"
+ $pie.images[:basket].should == "http://foo.com/basket.png"
end
- $pie.images[:ship].should == "http://foo.com/ship.png"
- end
- it "can declare multiple image statements" do
- make_pie do
- image ship:"http://foo.com/ship.png"
- image basket:"http://foo.com/basket.png"
+ it "can declare multiple images with one statement" do
+ make_pie do
+ image ship:"http://foo.com/ship.png",
+ basket:"http://foo.com/basket.png"
+ end
+ $pie.images[:ship].should == "http://foo.com/ship.png"
+ $pie.images[:basket].should == "http://foo.com/basket.png"
end
- $pie.images[:ship].should == "http://foo.com/ship.png"
- $pie.images[:basket].should == "http://foo.com/basket.png"
end
- it "can declare multiple images with one statement" do
- make_pie do
- image ship:"http://foo.com/ship.png",
- basket:"http://foo.com/basket.png"
+ describe "creates places" do
+ it "can create a place without a description" do
+ make_pie do
+ create_places do
+ ship
+ end
+ end
+ $pie.places[:ship].should == {}
+ end
+
+ it "cannot create a place if options are invalid (given as a symbol not a Hash)" do
+ make_pie do
+ create_places do
+ result = ship :invalid
+ result.should == nil
+ end
+ end
+ $pie.places[:ship].should == nil
end
- $pie.images[:ship].should == "http://foo.com/ship.png"
- $pie.images[:basket].should == "http://foo.com/basket.png"
+
end
+ describe "can access places" do
+ before do
+ make_pie do
+ create_places do
+ ship description:"ookina fune"
+ building description:"ookina biru"
+ tower description:"ookina towa"
+ end
+ end
+ end
+
+ it "which are accessible by named key" do
+ ship = $pie.places[:ship]
+ ship.should_not be_nil
+ ship[:description].should == "ookina fune"
+ end
+ it "resulting in 2 places" do
+ $pie.places.length.should == 3
+ end
+
+ it "and can find place after named place" do
+ building = $pie.places.after(:ship)
+ building.should_not be_nil
+ building[:description].should == "ookina biru"
+ end
+
+ it "and finds nil after last place" do
+ nothing = $pie.places.after(:tower)
+ nothing.should be_nil
+ end
+
+ it "and can find place before named place" do
+ building = $pie.places.before(:tower)
+ building.should_not be_nil
+ building[:description].should == "ookina biru"
+ end
+
+ it "and finds nil before first place" do
+ nothing = $pie.places.before(:ship)
+ nothing.should be_nil
+ end
+ end
end
|
blazingcloud/pie
|
9d56bb84f1f954ab05e00320d9defa42180578d6
|
refactored spec a little
|
diff --git a/pie_spec.rb b/pie_spec.rb
index 12171d9..c945bad 100644
--- a/pie_spec.rb
+++ b/pie_spec.rb
@@ -1,30 +1,30 @@
require File.expand_path(File.dirname(__FILE__) + '/pie')
describe "making pie" do
it "can declare an image" do
make_pie do
image ship:"http://foo.com/ship.png"
end
- $pie.images.should == {ship:"http://foo.com/ship.png"}
+ $pie.images[:ship].should == "http://foo.com/ship.png"
end
it "can declare multiple image statements" do
make_pie do
image ship:"http://foo.com/ship.png"
image basket:"http://foo.com/basket.png"
end
- $pie.images.should == {ship:"http://foo.com/ship.png",
- basket:"http://foo.com/basket.png"}
+ $pie.images[:ship].should == "http://foo.com/ship.png"
+ $pie.images[:basket].should == "http://foo.com/basket.png"
end
it "can declare multiple images with one statement" do
make_pie do
image ship:"http://foo.com/ship.png",
basket:"http://foo.com/basket.png"
end
- $pie.images.should == {ship:"http://foo.com/ship.png",
- basket:"http://foo.com/basket.png"}
+ $pie.images[:ship].should == "http://foo.com/ship.png"
+ $pie.images[:basket].should == "http://foo.com/basket.png"
end
end
|
blazingcloud/pie
|
2e5de209d258660d11dc9c8ea6a915e78e079a31
|
spec passes
|
diff --git a/pie.rb b/pie.rb
index 01e90f7..42abc53 100644
--- a/pie.rb
+++ b/pie.rb
@@ -1,71 +1,73 @@
require 'sinatra/base'
class Pie
class WebApp < Sinatra::Base
set :root, File.dirname(__FILE__)
get '/' do
"hello"
end
get '/:place_name' do
name = params[:place_name]
$current = name unless name.nil?
erb :image_page
end
end
- at_exit { puts "exit"; WebApp.run! }
+ at_exit { WebApp.run! if $0.include?("_spec")}
attr_accessor :places
+ attr_accessor :images
+
class Places < Array
def method_missing name, *args
puts "making a #{name} with #{args[0].inspect}"
self << {name.to_sym => args[0]}
end
end
def create_places(&block)
@places ||= Places.new
@places.instance_eval(&block)
end
def image(image_hash)
@images ||= {}
puts "--- set image"
puts image_hash.inspect
@images.merge!(image_hash)
end
def current_image
puts "------- current_image"
puts $current.inspect
puts @images.inspect
@images[$current.to_sym]
end
def current_description
puts "------- current_description"
puts $current
puts @places
place = @places[$current.to_sym]
place[:description] unless place.nil?
end
end
def make_pie(&block)
$pie = Pie.new
$pie.instance_eval(&block)
end
make_pie do
create_places do
ship description:"ookina funa"
building description:"ookina biru"
tower description:"ookina towa"
end
image ship:"images/big_ship.jpg",
building:"images/building.jpg",
tower:"images/tokyo_tower.jpg"
end
diff --git a/pie_spec.rb b/pie_spec.rb
index f027fbd..12171d9 100644
--- a/pie_spec.rb
+++ b/pie_spec.rb
@@ -1,25 +1,30 @@
require File.expand_path(File.dirname(__FILE__) + '/pie')
describe "making pie" do
- include Pie
it "can declare an image" do
- image ship:"http://foo.com/ship.png"
- @images.should == {ship:"http://foo.com/ship.png"}
+ make_pie do
+ image ship:"http://foo.com/ship.png"
+ end
+ $pie.images.should == {ship:"http://foo.com/ship.png"}
end
it "can declare multiple image statements" do
- image ship:"http://foo.com/ship.png"
- image basket:"http://foo.com/basket.png"
- @images.should == {ship:"http://foo.com/ship.png",
+ make_pie do
+ image ship:"http://foo.com/ship.png"
+ image basket:"http://foo.com/basket.png"
+ end
+ $pie.images.should == {ship:"http://foo.com/ship.png",
basket:"http://foo.com/basket.png"}
end
it "can declare multiple images with one statement" do
- image ship:"http://foo.com/ship.png",
+ make_pie do
+ image ship:"http://foo.com/ship.png",
basket:"http://foo.com/basket.png"
- @images.should == {ship:"http://foo.com/ship.png",
+ end
+ $pie.images.should == {ship:"http://foo.com/ship.png",
basket:"http://foo.com/basket.png"}
end
end
|
blazingcloud/pie
|
f3a537205f4f4bf29b3cdeb72527967e8e2c823f
|
add 1.9 requirement to README
|
diff --git a/README.md b/README.md
index e4e873e..a98429a 100644
--- a/README.md
+++ b/README.md
@@ -1,16 +1,18 @@
# Pie
A game development DSL, inspired by Yasuko Ohba's Ruby Kaigi talk and a late night coversaton with @knowtheory. Created by Sarah Allen with a little help from Chad Fowler.
This is very experimental and marginally useful. I don't think the spec works.
+Pie requires Ruby 1.9, because it is so cool.
+
There is a sample in book.rb. To use it:
ruby book.rb
then go to:
http://localhost:4567/ship
http://localhost:4567/building
http://localhost:4567/tower
|
blazingcloud/pie
|
94e879dd295711c867388fd0b2f534ac15b50f23
|
a little cleanup
|
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..38c8b2e
--- /dev/null
+++ b/README.md
@@ -0,0 +1,16 @@
+h1. Pie
+
+A game development DSL, inspired by Yasuko Ohba's Ruby Kaigi talk and a late night coversaton with @knowtheory. Created by Sarah Allen with a little help from Chad Fowler.
+
+This is very experimental and marginally useful. I don't think the spec works.
+
+There is a sample in book.rb. To use it:
+
+ruby book.rb
+
+then go to:
+http://localhost:4567/ship
+http://localhost:4567/building
+http://localhost:4567/tower
+
+
diff --git a/book.rb b/book.rb
index b85c0da..a8a5c9b 100644
--- a/book.rb
+++ b/book.rb
@@ -1,27 +1,21 @@
$LOAD_PATH << File.dirname(__FILE__)
require 'pie'
-require 'rubygems'
-require 'sinatra'
-
-class Book < Pie
- place :title, :description => "This is a book about big things"
- place :ship, :description =>"ookina funa"
- place :building, :description => "ookina biru"
- place :tower,:description => "ookina towa"
-
- image :ship => "images/big_ship.jpg",
- :building => "images/building.jpg",
- :tower => "images/tokyo_tower.jpg"
+def make_pie(&block)
+ $pie = Pie.new
+ $pie.instance_eval(&block)
end
-Book.start(:ship)
-get "/:place_name" do
- puts "$pie is #{$pie.inspect}"
+make_pie do
+ create_places do
+ ship description:"ookina funa"
+ building description:"ookina biru"
+ tower description:"ookina towa"
+ end
- name = params[:place_name]
- $current = name unless name.nil?
- erb :image_page
+ image ship:"images/big_ship.jpg",
+ building:"images/building.jpg",
+ tower:"images/tokyo_tower.jpg"
end
diff --git a/pie.rb b/pie.rb
index 04b6d14..01e90f7 100644
--- a/pie.rb
+++ b/pie.rb
@@ -1,37 +1,71 @@
-class Pie
- def self.image(image_hash)
- @@images ||= {}
- puts "--- set image"
- puts image_hash.inspect
- @@images.merge!(image_hash)
+require 'sinatra/base'
+
+class Pie
+ class WebApp < Sinatra::Base
+ set :root, File.dirname(__FILE__)
+
+ get '/' do
+ "hello"
+ end
+
+ get '/:place_name' do
+ name = params[:place_name]
+ $current = name unless name.nil?
+ erb :image_page
+ end
end
- def self.place name, options
- @@places ||= {}
- @@places[name.to_sym] = options
+ at_exit { puts "exit"; WebApp.run! }
+
+ attr_accessor :places
+ class Places < Array
+ def method_missing name, *args
+ puts "making a #{name} with #{args[0].inspect}"
+ self << {name.to_sym => args[0]}
+ end
end
- def self.start(starting_place)
- puts "starting at #{starting_place}"
- $pie = new
- puts "$pie is #{$pie.inspect}"
+ def create_places(&block)
+ @places ||= Places.new
+ @places.instance_eval(&block)
+ end
- $current = starting_place
+ def image(image_hash)
+ @images ||= {}
+ puts "--- set image"
+ puts image_hash.inspect
+ @images.merge!(image_hash)
end
- def current_image
+ def current_image
puts "------- current_image"
puts $current.inspect
- puts @@images.inspect
- @@images[$current.to_sym]
+ puts @images.inspect
+ @images[$current.to_sym]
end
def current_description
puts "------- current_description"
puts $current
- puts @@places
- place = @@places[$current.to_sym]
+ puts @places
+ place = @places[$current.to_sym]
place[:description] unless place.nil?
end
end
+def make_pie(&block)
+ $pie = Pie.new
+ $pie.instance_eval(&block)
+end
+
+make_pie do
+ create_places do
+ ship description:"ookina funa"
+ building description:"ookina biru"
+ tower description:"ookina towa"
+ end
+
+ image ship:"images/big_ship.jpg",
+ building:"images/building.jpg",
+ tower:"images/tokyo_tower.jpg"
+end
diff --git a/pie2.rb b/pie2.rb
index 01e90f7..c5d4af0 100644
--- a/pie2.rb
+++ b/pie2.rb
@@ -1,71 +1,55 @@
require 'sinatra/base'
class Pie
class WebApp < Sinatra::Base
set :root, File.dirname(__FILE__)
get '/' do
"hello"
end
get '/:place_name' do
name = params[:place_name]
$current = name unless name.nil?
erb :image_page
end
end
at_exit { puts "exit"; WebApp.run! }
attr_accessor :places
class Places < Array
def method_missing name, *args
puts "making a #{name} with #{args[0].inspect}"
self << {name.to_sym => args[0]}
end
end
def create_places(&block)
@places ||= Places.new
@places.instance_eval(&block)
end
def image(image_hash)
@images ||= {}
puts "--- set image"
puts image_hash.inspect
@images.merge!(image_hash)
end
def current_image
puts "------- current_image"
puts $current.inspect
puts @images.inspect
@images[$current.to_sym]
end
def current_description
puts "------- current_description"
puts $current
puts @places
place = @places[$current.to_sym]
place[:description] unless place.nil?
end
end
-def make_pie(&block)
- $pie = Pie.new
- $pie.instance_eval(&block)
-end
-
-make_pie do
- create_places do
- ship description:"ookina funa"
- building description:"ookina biru"
- tower description:"ookina towa"
- end
-
- image ship:"images/big_ship.jpg",
- building:"images/building.jpg",
- tower:"images/tokyo_tower.jpg"
-end
|
blazingcloud/pie
|
7fb9aac56b26afff9f6b51ede128ae8f1ec54453
|
OMG! It kinda works
|
diff --git a/pie2.rb b/pie2.rb
index d2a50c9..01e90f7 100644
--- a/pie2.rb
+++ b/pie2.rb
@@ -1,46 +1,71 @@
require 'sinatra/base'
class Pie
class WebApp < Sinatra::Base
+ set :root, File.dirname(__FILE__)
+
+ get '/' do
+ "hello"
+ end
+
+ get '/:place_name' do
+ name = params[:place_name]
+ $current = name unless name.nil?
+ erb :image_page
+ end
end
at_exit { puts "exit"; WebApp.run! }
attr_accessor :places
class Places < Array
def method_missing name, *args
puts "making a #{name} with #{args[0].inspect}"
self << {name.to_sym => args[0]}
end
end
def create_places(&block)
@places ||= Places.new
@places.instance_eval(&block)
end
def image(image_hash)
@images ||= {}
puts "--- set image"
puts image_hash.inspect
@images.merge!(image_hash)
end
+ def current_image
+ puts "------- current_image"
+ puts $current.inspect
+ puts @images.inspect
+ @images[$current.to_sym]
+ end
+
+ def current_description
+ puts "------- current_description"
+ puts $current
+ puts @places
+ place = @places[$current.to_sym]
+ place[:description] unless place.nil?
+ end
end
def make_pie(&block)
$pie = Pie.new
$pie.instance_eval(&block)
end
make_pie do
create_places do
ship description:"ookina funa"
building description:"ookina biru"
tower description:"ookina towa"
end
image ship:"images/big_ship.jpg",
building:"images/building.jpg",
tower:"images/tokyo_tower.jpg"
end
diff --git a/views/image_page.erb b/views/image_page.erb
index 606f0d6..b734f77 100644
--- a/views/image_page.erb
+++ b/views/image_page.erb
@@ -1,28 +1,30 @@
<html>
<head>
<style type="text/css">
.page {
width: 100%;
height: 100%;
margin-left: auto;
margin-right: auto;
}
- .page > img {
+ img {
margin-left: auto;
margin-right: auto;
+ width: 100%;
+ height: 100%;
}
p {
font-size: 36;
font-weight: bold;
text-align: center
}
</style>
</head>
<body>
<div class="page">
<img src="<%= $pie.current_image %>" alt="image" />
</div>
</body>
</html>
|
blazingcloud/pie
|
6784876442c5a8c7506c31fff6ca626f821fd990
|
run Sinatra web app
|
diff --git a/pie2.rb b/pie2.rb
index c8bec3c..d2a50c9 100644
--- a/pie2.rb
+++ b/pie2.rb
@@ -1,40 +1,46 @@
+require 'sinatra/base'
+
+class Pie
+ class WebApp < Sinatra::Base
+ end
+
+ at_exit { puts "exit"; WebApp.run! }
-class Pie
attr_accessor :places
class Places < Array
def method_missing name, *args
puts "making a #{name} with #{args[0].inspect}"
self << {name.to_sym => args[0]}
end
end
def create_places(&block)
@places ||= Places.new
@places.instance_eval(&block)
end
def image(image_hash)
@images ||= {}
puts "--- set image"
puts image_hash.inspect
@images.merge!(image_hash)
end
end
def make_pie(&block)
$pie = Pie.new
$pie.instance_eval(&block)
end
make_pie do
create_places do
ship description:"ookina funa"
building description:"ookina biru"
tower description:"ookina towa"
end
- image :ship => "images/big_ship.jpg",
- :building => "images/building.jpg",
- :tower => "images/tokyo_tower.jpg"
+ image ship:"images/big_ship.jpg",
+ building:"images/building.jpg",
+ tower:"images/tokyo_tower.jpg"
end
|
blazingcloud/pie
|
7869eaa87d2f3091246fa1161bf3e7a3991366ec
|
pie2 getting closer
|
diff --git a/app.rb b/app.rb
new file mode 100644
index 0000000..d96ae76
--- /dev/null
+++ b/app.rb
@@ -0,0 +1 @@
+require 'sinatra_lib'
diff --git a/book.rb b/book.rb
new file mode 100644
index 0000000..b85c0da
--- /dev/null
+++ b/book.rb
@@ -0,0 +1,27 @@
+$LOAD_PATH << File.dirname(__FILE__)
+require 'pie'
+require 'rubygems'
+require 'sinatra'
+
+
+class Book < Pie
+ place :title, :description => "This is a book about big things"
+ place :ship, :description =>"ookina funa"
+ place :building, :description => "ookina biru"
+ place :tower,:description => "ookina towa"
+
+ image :ship => "images/big_ship.jpg",
+ :building => "images/building.jpg",
+ :tower => "images/tokyo_tower.jpg"
+end
+Book.start(:ship)
+
+get "/:place_name" do
+ puts "$pie is #{$pie.inspect}"
+
+ name = params[:place_name]
+ $current = name unless name.nil?
+ erb :image_page
+end
+
+
diff --git a/credits.txt b/credits.txt
new file mode 100644
index 0000000..8829b1e
--- /dev/null
+++ b/credits.txt
@@ -0,0 +1,3 @@
+ship: http://www.flickr.com/photos/savannahgrandfather/297715985/sizes/o/
+building: http://www.flickr.com/photos/nikonvscanon/3453373352/sizes/o/
+tower: http://www.flickr.com/photos/twicepix/4086153702/
diff --git a/new b/new
new file mode 100644
index 0000000..1cca261
--- /dev/null
+++ b/new
@@ -0,0 +1,24 @@
+
+
+class Pie
+ class PlaceFactory
+ def ship options
+ put "making a ship with #{options.inspect}"
+ end
+ end
+ def create_places(&block)
+ @place_factory ||= PlaceFactory.new
+ @place_factory.instance_eval(&block)
+ end
+
+end
+
+
+pie do
+
+ create_places do
+ ship description:"dddd",
+ end
+
+
+end
diff --git a/pie.rb b/pie.rb
new file mode 100644
index 0000000..04b6d14
--- /dev/null
+++ b/pie.rb
@@ -0,0 +1,37 @@
+class Pie
+ def self.image(image_hash)
+ @@images ||= {}
+ puts "--- set image"
+ puts image_hash.inspect
+ @@images.merge!(image_hash)
+ end
+
+ def self.place name, options
+ @@places ||= {}
+ @@places[name.to_sym] = options
+ end
+
+ def self.start(starting_place)
+ puts "starting at #{starting_place}"
+ $pie = new
+ puts "$pie is #{$pie.inspect}"
+
+ $current = starting_place
+ end
+
+ def current_image
+ puts "------- current_image"
+ puts $current.inspect
+ puts @@images.inspect
+ @@images[$current.to_sym]
+ end
+
+ def current_description
+ puts "------- current_description"
+ puts $current
+ puts @@places
+ place = @@places[$current.to_sym]
+ place[:description] unless place.nil?
+ end
+end
+
diff --git a/pie2.rb b/pie2.rb
new file mode 100644
index 0000000..c8bec3c
--- /dev/null
+++ b/pie2.rb
@@ -0,0 +1,40 @@
+
+class Pie
+ attr_accessor :places
+ class Places < Array
+ def method_missing name, *args
+ puts "making a #{name} with #{args[0].inspect}"
+ self << {name.to_sym => args[0]}
+ end
+ end
+
+ def create_places(&block)
+ @places ||= Places.new
+ @places.instance_eval(&block)
+ end
+
+ def image(image_hash)
+ @images ||= {}
+ puts "--- set image"
+ puts image_hash.inspect
+ @images.merge!(image_hash)
+ end
+
+end
+
+def make_pie(&block)
+ $pie = Pie.new
+ $pie.instance_eval(&block)
+end
+
+make_pie do
+ create_places do
+ ship description:"ookina funa"
+ building description:"ookina biru"
+ tower description:"ookina towa"
+ end
+
+ image :ship => "images/big_ship.jpg",
+ :building => "images/building.jpg",
+ :tower => "images/tokyo_tower.jpg"
+end
diff --git a/pie_spec.rb b/pie_spec.rb
new file mode 100644
index 0000000..f027fbd
--- /dev/null
+++ b/pie_spec.rb
@@ -0,0 +1,25 @@
+require File.expand_path(File.dirname(__FILE__) + '/pie')
+
+describe "making pie" do
+ include Pie
+
+ it "can declare an image" do
+ image ship:"http://foo.com/ship.png"
+ @images.should == {ship:"http://foo.com/ship.png"}
+ end
+
+ it "can declare multiple image statements" do
+ image ship:"http://foo.com/ship.png"
+ image basket:"http://foo.com/basket.png"
+ @images.should == {ship:"http://foo.com/ship.png",
+ basket:"http://foo.com/basket.png"}
+ end
+
+ it "can declare multiple images with one statement" do
+ image ship:"http://foo.com/ship.png",
+ basket:"http://foo.com/basket.png"
+ @images.should == {ship:"http://foo.com/ship.png",
+ basket:"http://foo.com/basket.png"}
+ end
+
+end
diff --git a/public/images/big building.jpg b/public/images/big building.jpg
new file mode 100644
index 0000000..9bfe5fa
Binary files /dev/null and b/public/images/big building.jpg differ
diff --git a/public/images/big_ship.jpg b/public/images/big_ship.jpg
new file mode 100644
index 0000000..51557d7
Binary files /dev/null and b/public/images/big_ship.jpg differ
diff --git a/public/images/building.jpg b/public/images/building.jpg
new file mode 100644
index 0000000..9bfe5fa
Binary files /dev/null and b/public/images/building.jpg differ
diff --git a/public/images/tokyo_tower.jpg b/public/images/tokyo_tower.jpg
new file mode 100644
index 0000000..fe0e3bf
Binary files /dev/null and b/public/images/tokyo_tower.jpg differ
diff --git a/sinatra_lib.rb b/sinatra_lib.rb
new file mode 100644
index 0000000..01b05b1
--- /dev/null
+++ b/sinatra_lib.rb
@@ -0,0 +1,6 @@
+require 'rubygems'
+require 'sinatra'
+
+get '/' do
+ "hello"
+end
diff --git a/test.rb b/test.rb
new file mode 100644
index 0000000..c9dbbe4
--- /dev/null
+++ b/test.rb
@@ -0,0 +1,2 @@
+class Foo
+end
diff --git a/views/image_page.erb b/views/image_page.erb
new file mode 100644
index 0000000..606f0d6
--- /dev/null
+++ b/views/image_page.erb
@@ -0,0 +1,28 @@
+<html>
+<head>
+<style type="text/css">
+ .page {
+ width: 100%;
+ height: 100%;
+ margin-left: auto;
+ margin-right: auto;
+ }
+
+ .page > img {
+ margin-left: auto;
+ margin-right: auto;
+ }
+
+ p {
+ font-size: 36;
+ font-weight: bold;
+ text-align: center
+ }
+</style>
+</head>
+<body>
+<div class="page">
+ <img src="<%= $pie.current_image %>" alt="image" />
+</div>
+</body>
+</html>
diff --git a/views/image_page.rb b/views/image_page.rb
new file mode 100644
index 0000000..1e01831
--- /dev/null
+++ b/views/image_page.rb
@@ -0,0 +1,2 @@
+<img src="<%= @image %>" width="100%" height="100%"/>
+<p valign="bottom"><%= @description %></p>
|
tomelkin/calculator
|
b89582a49160524da6fc4fb87427400a0a15fde0
|
Add README file for display on GitHub homepage.
|
diff --git a/.idea/.rakeTasks b/.idea/.rakeTasks
index fc74464..ab8539e 100644
--- a/.idea/.rakeTasks
+++ b/.idea/.rakeTasks
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Settings><!--This file was automatically generated by Ruby plugin.
You are allowed to:
1. Remove rake task
2. Add existing rake tasks
To add existing rake tasks automatically delete this file and reload the project.
---><RakeGroup description="" fullCmd="" taksId="rake"><RakeTask description="Remove any temporary products" fullCmd="clean" taksId="clean" /><RakeTask description="Remove any generated file" fullCmd="clobber" taksId="clobber" /><RakeGroup description="" fullCmd="" taksId="test"><RakeTask description="Run tests for integration" fullCmd="test:integration" taksId="integration" /><RakeTask description="Run tests for units" fullCmd="test:units" taksId="units" /></RakeGroup></RakeGroup></Settings>
+--><RakeGroup description="" fullCmd="" taksId="rake"><RakeTask description="Remove any temporary products" fullCmd="clean" taksId="clean" /><RakeTask description="Remove any generated file" fullCmd="clobber" taksId="clobber" /><RakeGroup description="" fullCmd="" taksId="test"><RakeTask description="Run tests for integration" fullCmd="test:integration" taksId="integration" /><RakeTask description="Run tests for units" fullCmd="test:units" taksId="units" /></RakeGroup><RakeGroup description="" fullCmd="" taksId="macro"><RakeTask description="" fullCmd="macro:deploy" taksId="deploy" /></RakeGroup></RakeGroup></Settings>
diff --git a/.idea/misc.xml b/.idea/misc.xml
index b12d45d..28ec19e 100644
--- a/.idea/misc.xml
+++ b/.idea/misc.xml
@@ -1,15 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<project relativePaths="false" version="4">
<component name="DependencyValidationManager">
<option name="SKIP_IMPORT_STATEMENTS" value="false" />
</component>
<component name="ProjectDetails">
<option name="projectName" value="calculator" />
</component>
- <component name="ProjectRootManager" version="2" project-jdk-name="Ruby SDK 1.8.7 (/usr/bin/ruby)" project-jdk-type="RUBY_SDK" />
+ <component name="ProjectRootManager" version="2" project-jdk-name="Ruby SDK 1.8.6 (/usr/bin/ruby)" project-jdk-type="RUBY_SDK" />
<component name="SvnBranchConfigurationManager">
<option name="myVersion" value="124" />
<option name="mySupportsUserInfoFilter" value="true" />
</component>
</project>
diff --git a/.idea/vcs.xml b/.idea/vcs.xml
index 7fce3fd..fda546d 100644
--- a/.idea/vcs.xml
+++ b/.idea/vcs.xml
@@ -1,7 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project relativePaths="false" version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="" />
+ <mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
diff --git a/.idea/workspace.xml b/.idea/workspace.xml
index de0597a..2275b78 100644
--- a/.idea/workspace.xml
+++ b/.idea/workspace.xml
@@ -1,398 +1,368 @@
<?xml version="1.0" encoding="UTF-8"?>
<project relativePaths="false" version="4">
<component name="ChangeListManager">
- <list default="true" readonly="true" name="Default" comment="" />
+ <list default="true" readonly="true" name="Default" comment="">
+ <change type="MODIFICATION" beforePath="$PROJECT_DIR$/.idea/workspace.xml" afterPath="$PROJECT_DIR$/.idea/workspace.xml" />
+ </list>
<ignored path="calculator.iws" />
<ignored path=".idea/workspace.xml" />
</component>
<component name="ChangesViewManager" flattened_view="true" show_ignored="false" />
<component name="CreatePatchCommitExecutor">
<option name="PATCH_PATH" value="" />
<option name="REVERSE_PATCH" value="false" />
</component>
<component name="DaemonCodeAnalyzer">
<disable_hints />
</component>
<component name="FavoritesManager">
<favorites_list name="calculator" />
</component>
<component name="FileEditorManager">
<leaf>
<file leaf-file-name="calculator_test.rb" pinned="false" current="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/test/unit/calculator_test.rb">
<provider selected="true" editor-type-id="text-editor">
- <state line="92" column="78" selection-start="3314" selection-end="3322" vertical-scroll-proportion="0.0">
+ <state line="92" column="78" selection-start="3196" selection-end="3196" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
</entry>
</file>
<file leaf-file-name="calculator.rb" pinned="false" current="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/lib/calculator.rb">
<provider selected="true" editor-type-id="text-editor">
- <state line="18" column="7" selection-start="485" selection-end="485" vertical-scroll-proportion="0.0">
+ <state line="18" column="7" selection-start="395" selection-end="395" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
</entry>
</file>
- <file leaf-file-name="getting_started.txt" pinned="false" current="true" current-in-tab="true">
+ <file leaf-file-name="getting_started.txt" pinned="false" current="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/getting_started.txt">
<provider selected="true" editor-type-id="text-editor">
- <state line="284" column="47" selection-start="14883" selection-end="14883" vertical-scroll-proportion="0.5457464">
+ <state line="284" column="47" selection-start="14883" selection-end="14883" vertical-scroll-proportion="0.0">
+ <folding />
+ </state>
+ </provider>
+ </entry>
+ </file>
+ <file leaf-file-name="README.md" pinned="false" current="true" current-in-tab="true">
+ <entry file="file://$PROJECT_DIR$/README.md">
+ <provider selected="true" editor-type-id="text-editor">
+ <state line="15" column="16" selection-start="397" selection-end="397" vertical-scroll-proportion="0.23255815">
<folding />
</state>
</provider>
</entry>
</file>
</leaf>
</component>
<component name="FindManager">
<FindUsagesManager>
<setting name="OPEN_NEW_TAB" value="false" />
</FindUsagesManager>
</component>
+ <component name="Git.Settings">
+ <option name="GIT_EXECUTABLE" value="/usr/local/git/bin/git" />
+ </component>
<component name="ProjectLevelVcsManager">
<OptionsSetting value="true" id="Add" />
<OptionsSetting value="true" id="Remove" />
<OptionsSetting value="true" id="Checkout" />
<OptionsSetting value="true" id="Update" />
<OptionsSetting value="true" id="Status" />
<OptionsSetting value="true" id="Edit" />
<ConfirmationsSetting value="0" id="Add" />
<ConfirmationsSetting value="0" id="Remove" />
</component>
<component name="ProjectPane">
<subPane>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="calculator" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
</PATH>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="calculator" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="calculator" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
</PATH>
- <PATH>
- <PATH_ELEMENT>
- <option name="myItemId" value="calculator" />
- <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
- </PATH_ELEMENT>
- <PATH_ELEMENT>
- <option name="myItemId" value="calculator" />
- <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
- </PATH_ELEMENT>
- <PATH_ELEMENT>
- <option name="myItemId" value="test" />
- <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
- </PATH_ELEMENT>
- <PATH_ELEMENT>
- <option name="myItemId" value="unit" />
- <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
- </PATH_ELEMENT>
- </PATH>
- <PATH>
- <PATH_ELEMENT>
- <option name="myItemId" value="calculator" />
- <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
- </PATH_ELEMENT>
- <PATH_ELEMENT>
- <option name="myItemId" value="calculator" />
- <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
- </PATH_ELEMENT>
- <PATH_ELEMENT>
- <option name="myItemId" value="test" />
- <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
- </PATH_ELEMENT>
- <PATH_ELEMENT>
- <option name="myItemId" value="integration" />
- <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
- </PATH_ELEMENT>
- </PATH>
- <PATH>
- <PATH_ELEMENT>
- <option name="myItemId" value="calculator" />
- <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
- </PATH_ELEMENT>
- <PATH_ELEMENT>
- <option name="myItemId" value="calculator" />
- <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
- </PATH_ELEMENT>
- <PATH_ELEMENT>
- <option name="myItemId" value="test" />
- <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
- </PATH_ELEMENT>
- <PATH_ELEMENT>
- <option name="myItemId" value="fixtures" />
- <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
- </PATH_ELEMENT>
- <PATH_ELEMENT>
- <option name="myItemId" value="sample" />
- <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
- </PATH_ELEMENT>
- </PATH>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="calculator" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="calculator" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="tasks" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
</PATH>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="calculator" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="calculator" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="lib" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
</PATH>
</subPane>
</component>
<component name="ProjectReloadState">
<option name="STATE" value="0" />
</component>
<component name="ProjectView">
<navigator currentView="ProjectPane" proportions="0.5" version="1" splitterProportion="0.5">
<flattenPackages />
<showMembers />
<showModules />
<showLibraryContents />
<hideEmptyPackages />
<abbreviatePackageNames />
<showStructure ProjectPane="false" />
<autoscrollToSource />
<autoscrollFromSource />
<sortByType />
</navigator>
</component>
+ <component name="PropertiesComponent">
+ <property name="options.splitter.details.proportions" value="0.2" />
+ <property name="options.splitter.main.proportions" value="0.3" />
+ <property name="options.searchVisible" value="true" />
+ <property name="options.lastSelected" value="com.intellij.openapi.vcs.configurable.VcsManagerConfigurable$4" />
+ </component>
<component name="RunManager">
- <configuration default="true" type="RSpecRunConfigurationType" factoryName="RSpec">
+ <configuration default="true" type="RubyRunConfigurationType" factoryName="Ruby script">
<module name="" />
- <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="RUBY_ARGS" VALUE="-e STDOUT.sync=true;STDERR.sync=true;load($0=ARGV.shift)" />
- <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="WORK DIR" VALUE="" />
- <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="SHOULD_USE_SDK" VALUE="false" />
- <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="ALTERN_SDK_NAME" VALUE="" />
- <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="myPassParentEnvs" VALUE="true" />
+ <RUBY_RUN_CONFIG NAME="RUBY_ARGS" VALUE="-e STDOUT.sync=true;STDERR.sync=true;load($0=ARGV.shift)" />
+ <RUBY_RUN_CONFIG NAME="WORK DIR" VALUE="" />
+ <RUBY_RUN_CONFIG NAME="SHOULD_USE_SDK" VALUE="false" />
+ <RUBY_RUN_CONFIG NAME="ALTERN_SDK_NAME" VALUE="" />
+ <RUBY_RUN_CONFIG NAME="myPassParentEnvs" VALUE="true" />
<envs />
- <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="TESTS_FOLDER_PATH" VALUE="" />
- <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="TEST_SCRIPT_PATH" VALUE="" />
- <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="SPEC_RUNNER_PATH" VALUE="[none]" />
- <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="TEST_FILE_MASK" VALUE="**/*_spec.rb" />
- <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="SPEC_EXAMPLE_NAME" VALUE="" />
- <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="TEST_TEST_TYPE" VALUE="TEST_SCRIPT" />
- <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="SPEC_ARGS" VALUE="" />
- <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="RUN_SPECS_SEPARATELY" VALUE="false" />
- <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="USE_CUSTOM_SPEC_RUNNER" VALUE="false" />
+ <RUBY_RUN_CONFIG NAME="SCRIPT_PATH" VALUE="" />
+ <RUBY_RUN_CONFIG NAME="SCRIPT_ARGS" VALUE="" />
</configuration>
<configuration default="true" type="TestUnitRunConfigurationType" factoryName="Ruby test">
<module name="" />
<RTEST_RUN_CONFIG_SETTINGS_ID NAME="RUBY_ARGS" VALUE="-e STDOUT.sync=true;STDERR.sync=true;load($0=ARGV.shift)" />
<RTEST_RUN_CONFIG_SETTINGS_ID NAME="WORK DIR" VALUE="" />
<RTEST_RUN_CONFIG_SETTINGS_ID NAME="SHOULD_USE_SDK" VALUE="false" />
<RTEST_RUN_CONFIG_SETTINGS_ID NAME="ALTERN_SDK_NAME" VALUE="" />
<RTEST_RUN_CONFIG_SETTINGS_ID NAME="myPassParentEnvs" VALUE="true" />
<envs />
<RTEST_RUN_CONFIG_SETTINGS_ID NAME="TESTS_FOLDER_PATH" VALUE="" />
<RTEST_RUN_CONFIG_SETTINGS_ID NAME="TEST_SCRIPT_PATH" VALUE="" />
<RTEST_RUN_CONFIG_SETTINGS_ID NAME="TEST_CLASS_NAME" VALUE="" />
<RTEST_RUN_CONFIG_SETTINGS_ID NAME="TEST_FILE_MASK" VALUE="" />
<RTEST_RUN_CONFIG_SETTINGS_ID NAME="TEST_METHOD_NAME" VALUE="" />
<RTEST_RUN_CONFIG_SETTINGS_ID NAME="TEST_TEST_TYPE" VALUE="TEST_SCRIPT" />
<RTEST_RUN_CONFIG_SETTINGS_ID NAME="INHERITANCE_CHECK_DISABLED" VALUE="false" />
</configuration>
- <configuration default="true" type="RubyRunConfigurationType" factoryName="Ruby script">
+ <configuration default="true" type="RSpecRunConfigurationType" factoryName="RSpec">
<module name="" />
- <RUBY_RUN_CONFIG NAME="RUBY_ARGS" VALUE="-e STDOUT.sync=true;STDERR.sync=true;load($0=ARGV.shift)" />
- <RUBY_RUN_CONFIG NAME="WORK DIR" VALUE="" />
- <RUBY_RUN_CONFIG NAME="SHOULD_USE_SDK" VALUE="false" />
- <RUBY_RUN_CONFIG NAME="ALTERN_SDK_NAME" VALUE="" />
- <RUBY_RUN_CONFIG NAME="myPassParentEnvs" VALUE="true" />
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="RUBY_ARGS" VALUE="-e STDOUT.sync=true;STDERR.sync=true;load($0=ARGV.shift)" />
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="WORK DIR" VALUE="" />
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="SHOULD_USE_SDK" VALUE="false" />
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="ALTERN_SDK_NAME" VALUE="" />
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="myPassParentEnvs" VALUE="true" />
<envs />
- <RUBY_RUN_CONFIG NAME="SCRIPT_PATH" VALUE="" />
- <RUBY_RUN_CONFIG NAME="SCRIPT_ARGS" VALUE="" />
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="TESTS_FOLDER_PATH" VALUE="" />
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="TEST_SCRIPT_PATH" VALUE="" />
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="SPEC_RUNNER_PATH" VALUE="[none]" />
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="TEST_FILE_MASK" VALUE="**/*_spec.rb" />
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="SPEC_EXAMPLE_NAME" VALUE="" />
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="TEST_TEST_TYPE" VALUE="TEST_SCRIPT" />
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="SPEC_ARGS" VALUE="" />
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="USE_CUSTOM_SPEC_RUNNER" VALUE="false" />
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="DRB" VALUE="false" />
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="FULL_BACKTRACE" VALUE="false" />
</configuration>
<list size="0" />
</component>
<component name="ShelveChangesManager" show_recycled="false" />
<component name="SvnConfiguration">
<option name="USER" value="" />
<option name="PASSWORD" value="" />
<option name="LAST_MERGED_REVISION" />
<option name="UPDATE_RUN_STATUS" value="false" />
<option name="MERGE_DRY_RUN" value="false" />
<option name="MERGE_DIFF_USE_ANCESTRY" value="true" />
<option name="UPDATE_LOCK_ON_DEMAND" value="false" />
<option name="IGNORE_SPACES_IN_MERGE" value="false" />
<option name="DETECT_NESTED_COPIES" value="true" />
- <configuration useDefault="true">/home/tom/.subversion</configuration>
+ <configuration useDefault="true">/Users/administrator/.subversion</configuration>
<myIsUseDefaultProxy>false</myIsUseDefaultProxy>
</component>
<component name="ToolWindowManager">
- <frame x="0" y="24" width="1152" height="840" extended-state="6" />
- <editor active="true" />
+ <frame x="10" y="22" width="1260" height="911" extended-state="0" />
+ <editor active="false" />
<layout>
+ <window_info id="Web Preview" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" />
+ <window_info id="Dependency Viewer" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" />
<window_info id="Changes" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" />
+ <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="2" side_tool="false" />
<window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="6" side_tool="false" />
- <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="1" side_tool="false" />
- <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" />
- <window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.3250444" sideWeight="0.5" order="0" side_tool="false" />
- <window_info id="Dependency Viewer" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" />
- <window_info id="Web Preview" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" />
+ <window_info id="Project" active="true" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.32443365" sideWeight="0.5" order="0" side_tool="false" />
<window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="3" side_tool="false" />
- <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="2" side_tool="false" />
+ <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" />
<window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" />
- <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="4" side_tool="false" />
<window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="0" side_tool="false" />
+ <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="1" side_tool="false" />
+ <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="5" side_tool="false" />
<window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" />
- <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="0" side_tool="false" />
+ <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="4" side_tool="false" />
<window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="2" side_tool="false" />
- <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="5" side_tool="false" />
+ <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="0" side_tool="false" />
</layout>
</component>
<component name="VcsManagerConfiguration">
<option name="OFFER_MOVE_TO_ANOTHER_CHANGELIST_ON_PARTIAL_COMMIT" value="true" />
<option name="CHECK_CODE_SMELLS_BEFORE_PROJECT_COMMIT" value="true" />
<option name="PERFORM_UPDATE_IN_BACKGROUND" value="true" />
<option name="PERFORM_COMMIT_IN_BACKGROUND" value="true" />
<option name="PERFORM_EDIT_IN_BACKGROUND" value="true" />
<option name="PERFORM_CHECKOUT_IN_BACKGROUND" value="true" />
<option name="PERFORM_ADD_REMOVE_IN_BACKGROUND" value="true" />
<option name="PERFORM_ROLLBACK_IN_BACKGROUND" value="false" />
<option name="FORCE_NON_EMPTY_COMMENT" value="false" />
<option name="LAST_COMMIT_MESSAGE" />
<option name="OPTIMIZE_IMPORTS_BEFORE_PROJECT_COMMIT" value="false" />
<option name="REFORMAT_BEFORE_PROJECT_COMMIT" value="false" />
<option name="REFORMAT_BEFORE_FILE_COMMIT" value="false" />
<option name="FILE_HISTORY_DIALOG_COMMENTS_SPLITTER_PROPORTION" value="0.8" />
<option name="FILE_HISTORY_DIALOG_SPLITTER_PROPORTION" value="0.5" />
<option name="ACTIVE_VCS_NAME" />
<option name="UPDATE_GROUP_BY_PACKAGES" value="false" />
<option name="UPDATE_GROUP_BY_CHANGELIST" value="false" />
<option name="SHOW_FILE_HISTORY_AS_TREE" value="false" />
<option name="FILE_HISTORY_SPLITTER_PROPORTION" value="0.6" />
</component>
<component name="XDebuggerManager">
<breakpoint-manager />
</component>
<component name="editorHistoryManager">
<entry file="file://$PROJECT_DIR$/Rakefile">
<provider selected="true" editor-type-id="text-editor">
<state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/tasks/test.rake">
<provider selected="true" editor-type-id="text-editor">
<state line="1" column="0" selection-start="24" selection-end="24" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/test/integration/calculator_integration_test.rb">
<provider selected="true" editor-type-id="text-editor">
<state line="6" column="110" selection-start="590" selection-end="679" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/test/fixtures/sample/users.yml">
<provider selected="true" editor-type-id="text-editor">
<state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/init.rb">
<provider selected="true" editor-type-id="text-editor">
<state line="6" column="31" selection-start="141" selection-end="141" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/test/unit/unit_test_helper.rb">
<provider selected="true" editor-type-id="text-editor">
<state line="8" column="12" selection-start="275" selection-end="283" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/test/fixtures/sample/card_types.yml">
<provider selected="true" editor-type-id="text-editor">
<state line="4" column="10" selection-start="60" selection-end="60" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/test/fixtures/sample/card_types_property_definitions.yml">
<provider selected="true" editor-type-id="text-editor">
<state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/test/fixtures/sample/projects.yml">
<provider selected="true" editor-type-id="text-editor">
<state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/test/fixtures/sample/project_variables.yml">
<provider selected="true" editor-type-id="text-editor">
<state line="0" column="3" selection-start="3" selection-end="3" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/test/unit/fixture_loader.rb">
<provider selected="true" editor-type-id="text-editor">
<state line="85" column="52" selection-start="3190" selection-end="3234" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/test/unit/calculator_test.rb">
<provider selected="true" editor-type-id="text-editor">
- <state line="92" column="78" selection-start="3314" selection-end="3322" vertical-scroll-proportion="0.0">
+ <state line="92" column="78" selection-start="3196" selection-end="3196" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/lib/calculator.rb">
<provider selected="true" editor-type-id="text-editor">
- <state line="18" column="7" selection-start="485" selection-end="485" vertical-scroll-proportion="0.0">
+ <state line="18" column="7" selection-start="395" selection-end="395" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/getting_started.txt">
<provider selected="true" editor-type-id="text-editor">
- <state line="284" column="47" selection-start="14883" selection-end="14883" vertical-scroll-proportion="0.5457464">
+ <state line="284" column="47" selection-start="14883" selection-end="14883" vertical-scroll-proportion="0.0">
+ <folding />
+ </state>
+ </provider>
+ </entry>
+ <entry file="file://$PROJECT_DIR$/README.md">
+ <provider selected="true" editor-type-id="text-editor">
+ <state line="15" column="16" selection-start="397" selection-end="397" vertical-scroll-proportion="0.23255815">
<folding />
</state>
</provider>
</entry>
</component>
</project>
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..c1b0c39
--- /dev/null
+++ b/README.md
@@ -0,0 +1,21 @@
+Simple macro to allow users to write basic arithmetic expressions comprised of MQL statements.
+
+Once installed the calculator macro can be used like follows:
+
+<pre><code>
+{{
+ calculator
+ equation: a * (b + 3) % 5
+ terms:
+ - term: a
+ mql: select COUNT(*) where 'type' = 'iteration'
+ - term: b
+ mql: select MAX('planning estimate') where type = story
+
+}}
+</code></pre>
+
+* Supported arithmetic operators: + - * / % ( )
+* Any valid symbol name in Ruby can be used for a term identifier. Any number of terms can be used in an equation.
+* At the moment equation terms can only resolve to MQL statements.
+* If an MQL statement doesn't evaulate to a singular numeric value then an exception will be raised. e.g. if a result set of size > 1, or if the result is a string.
|
tomelkin/calculator
|
307bd8bee89b78f3f0d33548a8dc82b8a8ed8029
|
Adding modulus operator support. Works with numeric MQL queries, such as SUM, MIN, MAX, AVG, as well as Count(*). Refactored code and tests. Adding MIT license.
|
diff --git a/LICENSE.txt b/LICENSE.txt
new file mode 100644
index 0000000..6a1597f
--- /dev/null
+++ b/LICENSE.txt
@@ -0,0 +1,21 @@
+The MIT License
+
+Copyright (c) 2008 ThoughtWorks, Inc. All rights reserved.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/lib/calculator.rb b/lib/calculator.rb
index ca5bcbe..9d17016 100644
--- a/lib/calculator.rb
+++ b/lib/calculator.rb
@@ -1,35 +1,52 @@
class Calculator
def initialize(parameters, project, current_user)
@parameters = parameters
@project = project
@current_user = current_user
end
def execute
- equation = @parameters[:equation]
- @parameters[:terms].each do |term|
- mql_result = @project.execute_mql(term[:mql])
- pattern = Regexp.new('\b' + term[:term] + '\b')
- equation.gsub!(pattern, mql_result.to_s)
- end
+ equation = generate_equation
if (is_expression_numeric?(equation))
eval(equation)
else
raise RuntimeError.new("Equation to run contains non-numeric values: '#{equation}'")
end
end
-
def can_be_cached?
false # if appropriate, switch to true once you move your macro to production
end
private
+ def generate_equation
+ equation = @parameters['equation']
+ @parameters['terms'].each do |term|
+ substitute_term_for_mql_result equation, term
+ end
+ equation
+ end
+
+ def substitute_term_for_mql_result(equation, term)
+ mql_result = get_singular_mql_result term['mql']
+ pattern = Regexp.new('\b' + term['term'] + '\b')
+ equation.gsub!(pattern, mql_result)
+ end
+
+ def get_singular_mql_result(mql)
+ mql_result = @project.execute_mql(mql)
+
+ if (mql_result.length > 1)
+ raise RuntimeError.new("Equation term evaluated to give more than one result, should just evaluate to a number: '#{mql}'")
+ end
+ mql_result.first.values.first
+ end
+
def is_expression_numeric?(expression)
- expression.match(/^[\s\+\*\-\/0123456789\.\(\)]*$/) != nil
+ expression.match(/^[\s\+\*\-\/%0123456789\.\(\)]*$/) != nil
end
end
\ No newline at end of file
diff --git a/test/unit/calculator_test.rb b/test/unit/calculator_test.rb
index d4c94dd..ef3299b 100644
--- a/test/unit/calculator_test.rb
+++ b/test/unit/calculator_test.rb
@@ -1,102 +1,97 @@
require File.join(File.dirname(__FILE__), 'unit_test_helper')
class CalculatorTest < Test::Unit::TestCase
FIXTURE = 'sample'
- def test_macro_contents
- params = {:equation => '1 + 1',
- :terms => []}
- calculator = Calculator.new(params, project(FIXTURE), nil)
- result = calculator.execute
- assert result
+ def test_add
+ verify_count_calculator('a + b', {'a' => 96, 'b' => 6}, 102)
end
- def test_add_mql_results
- params = {:equation => 'a + b',
- :terms => [ {:term => 'a', :mql => "select 2"},
- {:term => 'b', :mql => "select 3"}]}
- project = project(FIXTURE)
- project.expects(:execute_mql).with("select 2").returns(2)
- project.expects(:execute_mql).with("select 3").returns(3)
- calculator = Calculator.new(params, project, nil)
- result = calculator.execute
- assert result == 5
+ def test_subtract
+ verify_count_calculator('a - b', {'a' => 96, 'b' => 6}, 90)
+ end
+ def test_divide
+ verify_count_calculator('a / b', {'a' => 96, 'b' => 6}, 16)
end
- def test_add_mql_results
- params = {:equation => 'a / (b - c)',
- :terms => [ {:term => 'a', :mql => "select 99"},
- {:term => 'b', :mql => "select 17"},
- {:term => 'c', :mql => "select 6"}]}
- project = project(FIXTURE)
- project.expects(:execute_mql).with("select 99").returns(99)
- project.expects(:execute_mql).with("select 17").returns(17)
- project.expects(:execute_mql).with("select 6").returns(6)
- calculator = Calculator.new(params, project, nil)
- result = calculator.execute
- assert result == 9
+ def test_multiply
+ verify_count_calculator('a * b', {'a' => 96, 'b' => 6}, 576)
+ end
+
+ def test_modulus
+ verify_count_calculator('a % b', {'a' => 17, 'b' => 5}, 2)
end
def test_adds_numbers
- params = {:equation => '1 + 2',
- :terms => []}
- calculator = Calculator.new(params, project(FIXTURE), nil)
- result = calculator.execute
- assert result == 3
+ verify_count_calculator('20 + 5', {}, 25)
end
def test_copes_with_terms_containing_numbers
- params = {:equation => 'a1 * a2',
- :terms => [ {:term => 'a1', :mql => "select 2"},
- {:term => 'a2', :mql => "select 3"}]}
- project = project(FIXTURE)
- project.expects(:execute_mql).with("select 2").returns(2)
- project.expects(:execute_mql).with("select 3").returns(3)
- calculator = Calculator.new(params, project, nil)
- result = calculator.execute
- assert result == 6
+ verify_count_calculator('a1 * a2', {'a1' => 2, 'a2' => 3}, 6)
end
def test_calculates_with_similar_variable_names
- params = {:equation => 'art + dart + artistic',
- :terms => [ {:term => 'art', :mql => "select 2"},
- {:term => 'dart', :mql => "select 3"},
- {:term => 'artistic', :mql => "select 4"}]}
+ verify_count_calculator('art + dart + artistic', {'art' => 2, 'dart' => 3, 'artistic' => 4}, 9)
+ end
+
+ def test_works_with_brackets
+ verify_count_calculator('(art + dart) * dart', {'art' => 2, 'dart' => 3}, 15)
+ end
+
+ def test_throws_exception_if_mql_returns_more_than_one_result
+ query = "select 'planning estimate' where type='story'"
+ params = {'equation' => 'a',
+ 'terms' => [ {'term' => 'a', 'mql' => query}]}
project = project(FIXTURE)
- project.expects(:execute_mql).with("select 2").returns(2)
- project.expects(:execute_mql).with("select 3").returns(3)
- project.expects(:execute_mql).with("select 4").returns(4)
+ project.expects(:execute_mql).with(query).returns([{'Planning Estimate' => '2'}, {'Planning Estimate' => '3'}])
calculator = Calculator.new(params, project, nil)
- result = calculator.execute
- assert result == 9
+ exception = assert_raise(RuntimeError) do
+ calculator.execute
+ end
+ assert_equal("Equation term evaluated to give more than one result, should just evaluate to a number: '#{query}'", exception.message)
end
- def test_works_with_brackets
- params = {:equation => '(art + dart) * dart',
- :terms => [ {:term => 'art', :mql => "select 2"},
- {:term => 'dart', :mql => "select 3"}]}
+ def test_gets_first_returned_value_for_mql_queries
+ query = "Select SUM('planning estimate') where type = 'story'"
+ params = {'equation' => 'x * 2',
+ 'terms' => [ {'term' => 'x', 'mql' => query}]
+ }
project = project(FIXTURE)
- project.expects(:execute_mql).with("select 2").returns(2)
- project.expects(:execute_mql).with("select 3").returns(3)
+ project.expects(:execute_mql).with(query).returns([{'Sum Planning Estimate' => '76.0000000000'}])
calculator = Calculator.new(params, project, nil)
result = calculator.execute
- assert result == 15
+ assert result == 152
end
def test_throws_exception_if_equation_contains_non_numeric_expressions
- params = {:equation => 'naughty',
- :terms => [ {:term => 'naughty', :mql => "select table_value"}]}
+ params = {'equation' => 'naughty',
+ 'terms' => [ {'term' => 'naughty', 'mql' => "Select 'name' where number = 123"}]}
project = project(FIXTURE)
- project.expects(:execute_mql).with("select table_value").returns("Dir.pwd")
+ project.expects(:execute_mql).with("Select 'name' where number = 123").returns([{"name" => "Dir.pwd"}])
Dir.expects(:pwd).never
exception = assert_raise(RuntimeError) do
calculator = Calculator.new(params, project, nil)
calculator.execute
end
assert_equal("Equation to run contains non-numeric values: 'Dir.pwd'", exception.message)
end
+
+ private
+
+ def verify_count_calculator(equation, terms, expected_result)
+ project = project(FIXTURE)
+ params = {'equation' => equation, 'terms' => []}
+ terms.each do |term, value|
+ mql_statement = "select count(*) where name = '#{term}'"
+ project.expects(:execute_mql).with(mql_statement).returns([{'Count ' => "#{value}"}])
+ params['terms'] << {'term' => term, 'mql' => mql_statement}
+ end
+
+ calculator = Calculator.new(params, project, nil)
+ assert calculator.execute == expected_result
+ end
end
\ No newline at end of file
|
tomelkin/calculator
|
2f753a35b1742f6bb8a40892c10514cf79654f9e
|
Throw exception if someone incorrectly enters an equation
|
diff --git a/lib/calculator.rb b/lib/calculator.rb
index 6ce4783..ca5bcbe 100644
--- a/lib/calculator.rb
+++ b/lib/calculator.rb
@@ -1,33 +1,35 @@
class Calculator
def initialize(parameters, project, current_user)
@parameters = parameters
@project = project
@current_user = current_user
end
def execute
equation = @parameters[:equation]
@parameters[:terms].each do |term|
mql_result = @project.execute_mql(term[:mql])
pattern = Regexp.new('\b' + term[:term] + '\b')
equation.gsub!(pattern, mql_result.to_s)
end
if (is_expression_numeric?(equation))
eval(equation)
+ else
+ raise RuntimeError.new("Equation to run contains non-numeric values: '#{equation}'")
end
end
def can_be_cached?
false # if appropriate, switch to true once you move your macro to production
end
private
def is_expression_numeric?(expression)
expression.match(/^[\s\+\*\-\/0123456789\.\(\)]*$/) != nil
end
end
\ No newline at end of file
diff --git a/test/unit/calculator_test.rb b/test/unit/calculator_test.rb
index 7262a38..d4c94dd 100644
--- a/test/unit/calculator_test.rb
+++ b/test/unit/calculator_test.rb
@@ -1,98 +1,102 @@
require File.join(File.dirname(__FILE__), 'unit_test_helper')
class CalculatorTest < Test::Unit::TestCase
FIXTURE = 'sample'
- #{{
- # calculator
- # equation: (x + y) / (a * 2)
- # terms:
- # - term: x
- # mql: select MAX('estimate') where 'type' = story and 'iteration' = ('current iteration')
- # - term: y
- # mql: select COUNT(*) where 'type' = 'iteration'
- # - term: a
- # mql: select 'velocity' where 'type' = 'release' and numbers in (72)
- #}}
-
-
def test_macro_contents
params = {:equation => '1 + 1',
:terms => []}
calculator = Calculator.new(params, project(FIXTURE), nil)
result = calculator.execute
assert result
end
def test_add_mql_results
params = {:equation => 'a + b',
:terms => [ {:term => 'a', :mql => "select 2"},
{:term => 'b', :mql => "select 3"}]}
project = project(FIXTURE)
project.expects(:execute_mql).with("select 2").returns(2)
project.expects(:execute_mql).with("select 3").returns(3)
calculator = Calculator.new(params, project, nil)
result = calculator.execute
assert result == 5
end
def test_add_mql_results
params = {:equation => 'a / (b - c)',
:terms => [ {:term => 'a', :mql => "select 99"},
{:term => 'b', :mql => "select 17"},
{:term => 'c', :mql => "select 6"}]}
project = project(FIXTURE)
project.expects(:execute_mql).with("select 99").returns(99)
project.expects(:execute_mql).with("select 17").returns(17)
project.expects(:execute_mql).with("select 6").returns(6)
calculator = Calculator.new(params, project, nil)
result = calculator.execute
assert result == 9
end
def test_adds_numbers
params = {:equation => '1 + 2',
:terms => []}
calculator = Calculator.new(params, project(FIXTURE), nil)
result = calculator.execute
assert result == 3
end
+ def test_copes_with_terms_containing_numbers
+ params = {:equation => 'a1 * a2',
+ :terms => [ {:term => 'a1', :mql => "select 2"},
+ {:term => 'a2', :mql => "select 3"}]}
+ project = project(FIXTURE)
+ project.expects(:execute_mql).with("select 2").returns(2)
+ project.expects(:execute_mql).with("select 3").returns(3)
+ calculator = Calculator.new(params, project, nil)
+ result = calculator.execute
+ assert result == 6
+ end
+
def test_calculates_with_similar_variable_names
params = {:equation => 'art + dart + artistic',
:terms => [ {:term => 'art', :mql => "select 2"},
{:term => 'dart', :mql => "select 3"},
{:term => 'artistic', :mql => "select 4"}]}
project = project(FIXTURE)
project.expects(:execute_mql).with("select 2").returns(2)
project.expects(:execute_mql).with("select 3").returns(3)
project.expects(:execute_mql).with("select 4").returns(4)
calculator = Calculator.new(params, project, nil)
result = calculator.execute
assert result == 9
end
def test_works_with_brackets
params = {:equation => '(art + dart) * dart',
:terms => [ {:term => 'art', :mql => "select 2"},
{:term => 'dart', :mql => "select 3"}]}
project = project(FIXTURE)
project.expects(:execute_mql).with("select 2").returns(2)
project.expects(:execute_mql).with("select 3").returns(3)
calculator = Calculator.new(params, project, nil)
result = calculator.execute
assert result == 15
end
- def test_cannot_use_equations_to_run_arbitary_ruby_code
+ def test_throws_exception_if_equation_contains_non_numeric_expressions
params = {:equation => 'naughty',
:terms => [ {:term => 'naughty', :mql => "select table_value"}]}
project = project(FIXTURE)
project.expects(:execute_mql).with("select table_value").returns("Dir.pwd")
+
Dir.expects(:pwd).never
- calculator = Calculator.new(params, project, nil)
- calculator.execute
+
+ exception = assert_raise(RuntimeError) do
+ calculator = Calculator.new(params, project, nil)
+ calculator.execute
+ end
+ assert_equal("Equation to run contains non-numeric values: 'Dir.pwd'", exception.message)
end
end
\ No newline at end of file
|
redsolution/django-snapshot
|
45b890e6b17f9e69a0430c3054e606a3682619fd
|
Added setup and deploy files
|
diff --git a/DESCRIPTION b/DESCRIPTION
new file mode 100644
index 0000000..e85e497
--- /dev/null
+++ b/DESCRIPTION
@@ -0,0 +1 @@
+Django backup and restore tool. Handle upload files and database
\ No newline at end of file
diff --git a/README b/README
new file mode 120000
index 0000000..92cacd2
--- /dev/null
+++ b/README
@@ -0,0 +1 @@
+README.rst
\ No newline at end of file
diff --git a/README.rst b/README.rst
new file mode 100644
index 0000000..a2fee5c
--- /dev/null
+++ b/README.rst
@@ -0,0 +1,43 @@
+===============
+django-snapshot
+===============
+
+Installation:
+=============
+
+1. Add ``snapshot`` to ``INSTALLED_APPS`` in your ``settings.py`` within your django project.
+
+
+Usage
+======
+
+Use management command ``snap``
+
+ ``./manage.py snap``
+
+*help:*
+
+* snap save - take a snapshot at current time
+* snap restore [i] - restore from [i] snapshot (0 by default)
+* snap list - list all available snapshots
+
+
+How it works:
+=============
+
+Program create \*.tar.gz archive with files:
+
+ **info.json** - JSON description of archive's contents for ``restore`` command
+
+ **directory_backup.2011-01-01.tar** - backup of upload directory
+
+ **database_postgres_backup.2011-01-01.sql** - SQL database dump
+
+All files created and restored automatically, you do not need to bother of
+their structure.
+
+Restrictions:
+==============
+
+Django-snapshot works now only with PostgreSQL database. Nor sqlite or MySQL are not supported.
+If you have any suggestions, email developers. Any feedback is welcome.
\ No newline at end of file
diff --git a/setup.py b/setup.py
new file mode 100644
index 0000000..7053f89
--- /dev/null
+++ b/setup.py
@@ -0,0 +1,45 @@
+# -*- coding: utf-8 -*-
+import os
+from setuptools import setup, find_packages
+
+# Utility function to read the README file.
+# Used for the long_description. It's nice, because now 1) we have a top level
+# README file and 2) it's easier to type in the README file than to put a raw
+# string in below ...
+def read(fname):
+ try:
+ return open(os.path.join(os.path.dirname(__file__), fname)).read()
+ except IOError:
+ return ''
+
+setup(
+ name="django-snapshot",
+ version=__import__('snapshot').__version__,
+ description=read('DESCRIPTION'),
+ license="GPLv3",
+ keywords="django snapshot backup restore tool",
+
+ author="Ivan Gromov",
+ author_email="ivan.gromov@redsolution.ru",
+
+ maintainer="Ivan Gromov",
+ maintainer_email="ivan.gromov@redsolution.ru",
+
+ classifiers=[
+ 'Development Status :: 3 - Alpha',
+ 'Intended Audience :: Developers',
+ 'License :: OSI Approved :: GNU General Public License (GPL)',
+ 'Framework :: Django',
+ 'Environment :: Web Environment',
+ 'Natural Language :: Russian',
+ 'Natural Language :: English',
+ 'Operating System :: OS Independent',
+ 'Programming Language :: Python',
+ 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
+ ],
+ packages=find_packages(),
+ install_requires=[],
+ include_package_data=True,
+ zip_safe=False,
+ long_description=read('README'),
+)
diff --git a/snapshot/__init__.py b/snapshot/__init__.py
index e69de29..541f859 100644
--- a/snapshot/__init__.py
+++ b/snapshot/__init__.py
@@ -0,0 +1 @@
+__version__ = '0.1.0'
\ No newline at end of file
|
redsolution/django-snapshot
|
e75ceee3c765195942a277b6f04ec5eaf818a1bc
|
Fixed upload root dir
|
diff --git a/snapshot/models.py b/snapshot/models.py
index 2994bfc..e7f0fd4 100644
--- a/snapshot/models.py
+++ b/snapshot/models.py
@@ -1,301 +1,302 @@
# -*- coding: utf-8 -*-
from django.utils import simplejson
from shutil import rmtree
from snapshot import settings
from subprocess import Popen, PIPE, call
from snapshot.settings import SNAPSHOT_TARGETS, SNAPSHOTS_DIR
from snapshot.utils import import_item
import datetime
import logging
import os
import sys
logging.getLogger().setLevel(logging.DEBUG)
class MustOverride(Exception):
pass
class BackupTarget(object):
'''Class for main targets to backup and restore
It supposed to be overriden by database and filesystem extensions
'''
name = 'backup_target'
dump_file = None
unpack_path = ''
def snapshot(self):
raise MustOverride
def restore(self, dump):
raise MustOverride
def save_settings(self):
'''
Return JSON string with target name and target dump file
'''
return {
'name': self.name,
'dump_file': self.dump_file,
}
def load_settings(self, json):
'''
Load data from dictionary
'''
for item in json:
if item.get('name') == self.name:
self.dump_file = item.get('dump_file')
#===============================================================================
# Database snapshots
#===============================================================================
class Database(BackupTarget):
'''Database snapshot representation'''
connection_settings = {
'dbname': None,
'host': None,
'port': None,
'user': None,
'password': None,
}
encoding = 'UTF-8'
def __init__(self, settings_module):
self.connection_settings['dbname'] = getattr(settings_module, 'DATABASE_NAME')
self.connection_settings['host'] = getattr(settings_module, 'DATABASE_HOST', '127.0.0.1')
self.connection_settings['port'] = getattr(settings_module, 'DATABASE_PORT')
self.connection_settings['user'] = getattr(settings_module, 'DATABASE_USER')
self.connection_settings['password'] = getattr(settings_module, 'DATABASE_PASSWORD')
return super(Database, self).__init__()
class PostgresDatabase(Database):
name = 'postgres'
def _re_create_database(self):
return '\n'.join([
'\connect postgres;',
'DROP DATABASE %s;' % self.connection_settings['dbname'],
"CREATE DATABASE %s WITH OWNER %s ENCODING='%s';" % (
self.connection_settings['dbname'],
self.connection_settings['user'],
self.encoding,
),
'\connect %s;' % self.connection_settings['dbname'],
'',
])
def _authenticate(self):
if 'user' in self.connection_settings:
os.environ['PGUSER'] = self.connection_settings['user']
if 'password' in self.connection_settings:
os.environ['PGPASSWORD'] = self.connection_settings['password']
if 'dbname' in self.connection_settings:
os.environ['PGDATABASE'] = self.connection_settings['dbname']
def snapshot(self):
'''Make a snapshot of database. File in sql format supposed to be written on disk'''
logging.info('Taking a snapshot')
args = []
self._authenticate()
if 'host' in self.connection_settings:
args += ['--host=%s' % self.connection_settings['host']]
if 'port' in self.connection_settings:
args += ['--port=%s' % self.connection_settings['port']]
if self.connection_settings['dbname']:
args += [self.connection_settings['dbname']]
command = 'pg_dump %s' % (' '.join(args))
pipe = Popen(command, shell=True, stdin=PIPE, stdout=PIPE)
(stdout, stderr) = pipe.communicate(self.connection_settings['password'])
if pipe.wait() != 0:
logging.error('Error in database snapshot')
else:
logging.info('Database snapshot finished')
self.dump_file = 'database_postgres_backup.%s.sql' % (
datetime.datetime.now().strftime('%Y-%m-%d_%H-%M'))
file = open(os.path.join(settings.SNAPSHOTS_DIR, self.dump_file), 'w')
# save dump to file
file.write(self._re_create_database())
file.write(stdout)
file.close()
def restore(self):
'''Restore from sql file. Filename should be provided in self.dump_file'''
if not self.dump_file:
logging.error('Restore filename is None. Aborting')
return
logging.info('Restoring from %s' % self.dump_file)
args = []
self._authenticate()
if 'host' in self.connection_settings:
args += ['--host=%s' % self.connection_settings['host']]
if 'port' in self.connection_settings:
args += ['--port=%s' % self.connection_settings['port']]
command = 'psql %s < %s' % (' '.join(args), os.path.join(
self.unpack_path, self.dump_file))
pipe = Popen(command, shell=True, stdin=PIPE, stdout=PIPE)
if pipe.wait() != 0:
logging.error('Error while restoring')
else:
logging.info('Restored successfully')
#===============================================================================
# Directory snapshots
#===============================================================================
class Directory(BackupTarget):
'''File directory backup target'''
# TODO: filemask = ''
backup_dir = None
remove_old_files = True
def __init__(self, backup_dir):
self.backup_dir = backup_dir
return super(Directory, self).__init__()
def snapshot(self):
logging.info('Taking a snapshot')
self.dump_file = 'directory_backup.%s.tar' % (
datetime.datetime.now().strftime('%Y-%m-%d_%H-%M'))
command = 'tar cf %s -C %s .' % (os.path.join(
settings.SNAPSHOTS_DIR, self.dump_file), self.backup_dir)
pipe = Popen(command, shell=True)
if pipe.wait() != 0:
logging.error('Error while snapshot directory')
else:
logging.info('Snapshot directory successfully')
def restore(self):
if not self.dump_file:
logging.error('Restore filename is None. Aborting')
return
logging.info('Restoring from %s' % self.dump_file)
if self.remove_old_files:
# do not remove backup dir itself!
for root, dirs, files in os.walk(self.backup_dir, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
command = 'tar xf %s -C %s .' % (os.path.join(self.unpack_path,
self.dump_file), self.backup_dir)
pipe = Popen(command, shell=True)
if pipe.wait() != 0:
logging.error('Error while restoring directory')
else:
logging.info('Directory restored successfully')
class MediaDirectory(Directory):
name = 'media'
def __init__(self, settings_module):
return super(MediaDirectory, self).__init__(settings_module.MEDIA_ROOT)
class MediaUploadDirectory(Directory):
name = 'media_upload'
def __init__(self, settings_module):
# try import UPLOAD ROOT from settings, fault to 'upload'
- upload_dir = getattr(settings_module, 'UPLOAD_ROOT', None)
+ upload_root = getattr(settings_module, 'UPLOAD_ROOT', None)
+ upload_dir = os.path.join(settings_module.MEDIA_ROOT, upload_root)
if not upload_dir:
upload_dir = os.path.join(settings_module.MEDIA_ROOT, 'upload')
return super(MediaUploadDirectory, self).__init__(upload_dir)
#===============================================================================
# Collating objects class
#===============================================================================
class SnapSite(object):
'''A Django site snapshot
Attributes:
media - path to media directory
database - dictionary with database settings
settings - imported settings module from the site
'''
targets = []
def __init__(self, arg_settings=None):
if arg_settings:
django_settings = arg_settings
else:
from django.conf import settings
django_settings = settings
# get targets
for target_classname in SNAPSHOT_TARGETS:
Target = import_item(target_classname)
self.targets.append(Target(django_settings))
# create snapshots folder if not exists
if not os.path.exists(SNAPSHOTS_DIR):
os.mkdir(SNAPSHOTS_DIR)
return super(SnapSite, self).__init__()
def snapshot(self):
for target in self.targets:
target.snapshot()
# save settings to file
json_file = open(os.path.join(SNAPSHOTS_DIR, 'info.json'), 'w')
json_file.write(simplejson.dumps(
[target.save_settings() for target in self.targets],
indent=4,
))
json_file.close()
# and gzip contents to snapshot
archive_name = 'snapshot.%s.tar.gz' % (datetime.datetime.now().strftime('%Y-%m-%d_%H-%M'))
command = 'tar czf %(archive_name)s --remove-files -C %(path)s %(files)s ' % ({
'archive_name': os.path.join(SNAPSHOTS_DIR, archive_name),
'path': SNAPSHOTS_DIR,
'files': ' '.join([target.dump_file for target in self.targets] + ['info.json']),
})
pipe = Popen(command, shell=True)
if pipe.wait() != 0:
logging.error('Error while snapshot')
else:
logging.info('Snapshot successfully')
def restore(self, filename):
# first, unpack snapshot to temporary directory
unpack_path = os.path.join(SNAPSHOTS_DIR, 'tmp')
# delete old tmp directory if exixsts
if os.path.exists(unpack_path):
rmtree(unpack_path)
os.mkdir(unpack_path)
pipe = Popen('tar xf %s -C %s' % (os.path.join(SNAPSHOTS_DIR,
filename), unpack_path), shell=True)
pipe.wait()
# read settings from file
json_settings_file = open(os.path.join(SNAPSHOTS_DIR, 'tmp/info.json'), 'r')
json_settings = simplejson.loads(json_settings_file.read())
# load settings into target instances
for target in self.targets:
target.unpack_path = unpack_path
target.load_settings(json_settings)
# restore
for target in self.targets:
target.restore()
# remove tmp dir
rmtree(unpack_path)
|
redsolution/django-snapshot
|
b9048b418316c04f83e7ba88392f63c5dfe7f4af
|
Fixed order of snapshots, changed directory restoring
|
diff --git a/snapshot/management/commands/snap.py b/snapshot/management/commands/snap.py
index cfe25e9..04bf19e 100644
--- a/snapshot/management/commands/snap.py
+++ b/snapshot/management/commands/snap.py
@@ -1,55 +1,55 @@
# -*- coding: utf-8 -*-
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from optparse import OptionParser
from snapshot.models import SnapSite
from snapshot import settings as snapshot_settings
import os
class Command(BaseCommand):
help = '''Usage:
snap save - take a snapshot at current time
snap restore [i] - restore from [i] snapshot (0 by default)
snap list - list all available snapshots
'''
def handle(self, *args, **options):
if args:
action = args[0]
else:
action = None
# TODO: check settings directory
if action == 'save':
site = SnapSite(settings)
site.snapshot()
elif action == 'restore':
if len(args) > 1:
try:
number = int(args[1])
except ValueError:
raise CommandError('restre second argument must be digit')
else:
number = 0
try:
snapshots = os.listdir(snapshot_settings.SNAPSHOTS_DIR)
- snapshots = sorted(snapshots)
+ snapshots = sorted(snapshots, reverse=True)
snapshot_filename = snapshots[number]
except IndexError:
raise CommandError('Incorrect snapshot number')
except OSError:
raise CommandError("Snapshots wasn't created")
site = SnapSite(settings)
site.restore(snapshot_filename)
elif action == 'list':
try:
snapshots = os.listdir(snapshot_settings.SNAPSHOTS_DIR)
- snapshots = sorted(snapshots)
+ snapshots = sorted(snapshots, reverse=True)
except OSError:
raise CommandError("Snapshots wasn't created")
for i in range(len(snapshots)):
print '%d: %s' % (i, snapshots[i])
else:
print self.help
diff --git a/snapshot/models.py b/snapshot/models.py
index fc8fe2f..2994bfc 100644
--- a/snapshot/models.py
+++ b/snapshot/models.py
@@ -1,297 +1,301 @@
# -*- coding: utf-8 -*-
from django.utils import simplejson
from shutil import rmtree
from snapshot import settings
from subprocess import Popen, PIPE, call
from snapshot.settings import SNAPSHOT_TARGETS, SNAPSHOTS_DIR
from snapshot.utils import import_item
import datetime
import logging
import os
import sys
logging.getLogger().setLevel(logging.DEBUG)
class MustOverride(Exception):
pass
class BackupTarget(object):
'''Class for main targets to backup and restore
It supposed to be overriden by database and filesystem extensions
'''
name = 'backup_target'
dump_file = None
unpack_path = ''
def snapshot(self):
raise MustOverride
def restore(self, dump):
raise MustOverride
def save_settings(self):
'''
Return JSON string with target name and target dump file
'''
return {
'name': self.name,
'dump_file': self.dump_file,
}
def load_settings(self, json):
'''
Load data from dictionary
'''
for item in json:
if item.get('name') == self.name:
self.dump_file = item.get('dump_file')
#===============================================================================
# Database snapshots
#===============================================================================
class Database(BackupTarget):
'''Database snapshot representation'''
connection_settings = {
'dbname': None,
'host': None,
'port': None,
'user': None,
'password': None,
}
encoding = 'UTF-8'
def __init__(self, settings_module):
self.connection_settings['dbname'] = getattr(settings_module, 'DATABASE_NAME')
self.connection_settings['host'] = getattr(settings_module, 'DATABASE_HOST', '127.0.0.1')
self.connection_settings['port'] = getattr(settings_module, 'DATABASE_PORT')
self.connection_settings['user'] = getattr(settings_module, 'DATABASE_USER')
self.connection_settings['password'] = getattr(settings_module, 'DATABASE_PASSWORD')
return super(Database, self).__init__()
class PostgresDatabase(Database):
name = 'postgres'
def _re_create_database(self):
return '\n'.join([
'\connect postgres;',
'DROP DATABASE %s;' % self.connection_settings['dbname'],
"CREATE DATABASE %s WITH OWNER %s ENCODING='%s';" % (
self.connection_settings['dbname'],
self.connection_settings['user'],
self.encoding,
),
'\connect %s;' % self.connection_settings['dbname'],
'',
])
def _authenticate(self):
if 'user' in self.connection_settings:
os.environ['PGUSER'] = self.connection_settings['user']
if 'password' in self.connection_settings:
os.environ['PGPASSWORD'] = self.connection_settings['password']
if 'dbname' in self.connection_settings:
os.environ['PGDATABASE'] = self.connection_settings['dbname']
def snapshot(self):
'''Make a snapshot of database. File in sql format supposed to be written on disk'''
logging.info('Taking a snapshot')
args = []
self._authenticate()
if 'host' in self.connection_settings:
args += ['--host=%s' % self.connection_settings['host']]
if 'port' in self.connection_settings:
args += ['--port=%s' % self.connection_settings['port']]
if self.connection_settings['dbname']:
args += [self.connection_settings['dbname']]
command = 'pg_dump %s' % (' '.join(args))
pipe = Popen(command, shell=True, stdin=PIPE, stdout=PIPE)
(stdout, stderr) = pipe.communicate(self.connection_settings['password'])
if pipe.wait() != 0:
logging.error('Error in database snapshot')
else:
logging.info('Database snapshot finished')
self.dump_file = 'database_postgres_backup.%s.sql' % (
datetime.datetime.now().strftime('%Y-%m-%d_%H-%M'))
file = open(os.path.join(settings.SNAPSHOTS_DIR, self.dump_file), 'w')
# save dump to file
file.write(self._re_create_database())
file.write(stdout)
file.close()
def restore(self):
'''Restore from sql file. Filename should be provided in self.dump_file'''
if not self.dump_file:
logging.error('Restore filename is None. Aborting')
return
logging.info('Restoring from %s' % self.dump_file)
args = []
self._authenticate()
if 'host' in self.connection_settings:
args += ['--host=%s' % self.connection_settings['host']]
if 'port' in self.connection_settings:
args += ['--port=%s' % self.connection_settings['port']]
command = 'psql %s < %s' % (' '.join(args), os.path.join(
self.unpack_path, self.dump_file))
pipe = Popen(command, shell=True, stdin=PIPE, stdout=PIPE)
if pipe.wait() != 0:
logging.error('Error while restoring')
else:
logging.info('Restored successfully')
#===============================================================================
# Directory snapshots
#===============================================================================
class Directory(BackupTarget):
'''File directory backup target'''
# TODO: filemask = ''
backup_dir = None
remove_old_files = True
def __init__(self, backup_dir):
self.backup_dir = backup_dir
return super(Directory, self).__init__()
def snapshot(self):
logging.info('Taking a snapshot')
self.dump_file = 'directory_backup.%s.tar' % (
datetime.datetime.now().strftime('%Y-%m-%d_%H-%M'))
command = 'tar cf %s -C %s .' % (os.path.join(
settings.SNAPSHOTS_DIR, self.dump_file), self.backup_dir)
pipe = Popen(command, shell=True)
if pipe.wait() != 0:
logging.error('Error while snapshot directory')
else:
logging.info('Snapshot directory successfully')
def restore(self):
if not self.dump_file:
logging.error('Restore filename is None. Aborting')
return
logging.info('Restoring from %s' % self.dump_file)
if self.remove_old_files:
- rmtree(self.backup_dir)
- os.mkdir(self.backup_dir)
+ # do not remove backup dir itself!
+ for root, dirs, files in os.walk(self.backup_dir, topdown=False):
+ for name in files:
+ os.remove(os.path.join(root, name))
+ for name in dirs:
+ os.rmdir(os.path.join(root, name))
command = 'tar xf %s -C %s .' % (os.path.join(self.unpack_path,
self.dump_file), self.backup_dir)
pipe = Popen(command, shell=True)
if pipe.wait() != 0:
logging.error('Error while restoring directory')
else:
logging.info('Directory restored successfully')
class MediaDirectory(Directory):
name = 'media'
def __init__(self, settings_module):
return super(MediaDirectory, self).__init__(settings_module.MEDIA_ROOT)
class MediaUploadDirectory(Directory):
name = 'media_upload'
def __init__(self, settings_module):
# try import UPLOAD ROOT from settings, fault to 'upload'
upload_dir = getattr(settings_module, 'UPLOAD_ROOT', None)
if not upload_dir:
upload_dir = os.path.join(settings_module.MEDIA_ROOT, 'upload')
return super(MediaUploadDirectory, self).__init__(upload_dir)
#===============================================================================
# Collating objects class
#===============================================================================
class SnapSite(object):
'''A Django site snapshot
Attributes:
media - path to media directory
database - dictionary with database settings
settings - imported settings module from the site
'''
targets = []
def __init__(self, arg_settings=None):
if arg_settings:
django_settings = arg_settings
else:
from django.conf import settings
django_settings = settings
# get targets
for target_classname in SNAPSHOT_TARGETS:
Target = import_item(target_classname)
self.targets.append(Target(django_settings))
# create snapshots folder if not exists
if not os.path.exists(SNAPSHOTS_DIR):
os.mkdir(SNAPSHOTS_DIR)
return super(SnapSite, self).__init__()
def snapshot(self):
for target in self.targets:
target.snapshot()
# save settings to file
json_file = open(os.path.join(SNAPSHOTS_DIR, 'info.json'), 'w')
json_file.write(simplejson.dumps(
[target.save_settings() for target in self.targets],
indent=4,
))
json_file.close()
# and gzip contents to snapshot
archive_name = 'snapshot.%s.tar.gz' % (datetime.datetime.now().strftime('%Y-%m-%d_%H-%M'))
command = 'tar czf %(archive_name)s --remove-files -C %(path)s %(files)s ' % ({
'archive_name': os.path.join(SNAPSHOTS_DIR, archive_name),
'path': SNAPSHOTS_DIR,
'files': ' '.join([target.dump_file for target in self.targets] + ['info.json']),
})
pipe = Popen(command, shell=True)
if pipe.wait() != 0:
logging.error('Error while snapshot')
else:
logging.info('Snapshot successfully')
def restore(self, filename):
# first, unpack snapshot to temporary directory
unpack_path = os.path.join(SNAPSHOTS_DIR, 'tmp')
# delete old tmp directory if exixsts
if os.path.exists(unpack_path):
rmtree(unpack_path)
os.mkdir(unpack_path)
pipe = Popen('tar xf %s -C %s' % (os.path.join(SNAPSHOTS_DIR,
filename), unpack_path), shell=True)
pipe.wait()
# read settings from file
json_settings_file = open(os.path.join(SNAPSHOTS_DIR, 'tmp/info.json'), 'r')
json_settings = simplejson.loads(json_settings_file.read())
# load settings into target instances
for target in self.targets:
target.unpack_path = unpack_path
target.load_settings(json_settings)
# restore
for target in self.targets:
target.restore()
# remove tmp dir
rmtree(unpack_path)
|
redsolution/django-snapshot
|
9732112f5b7433103d385926e70917aa254c8a66
|
Add upload directory snapshot by default
|
diff --git a/snapshot/models.py b/snapshot/models.py
index a425fd7..fc8fe2f 100644
--- a/snapshot/models.py
+++ b/snapshot/models.py
@@ -1,287 +1,297 @@
# -*- coding: utf-8 -*-
from django.utils import simplejson
from shutil import rmtree
from snapshot import settings
from subprocess import Popen, PIPE, call
from snapshot.settings import SNAPSHOT_TARGETS, SNAPSHOTS_DIR
from snapshot.utils import import_item
import datetime
import logging
import os
import sys
logging.getLogger().setLevel(logging.DEBUG)
class MustOverride(Exception):
pass
class BackupTarget(object):
'''Class for main targets to backup and restore
It supposed to be overriden by database and filesystem extensions
'''
name = 'backup_target'
dump_file = None
unpack_path = ''
def snapshot(self):
raise MustOverride
def restore(self, dump):
raise MustOverride
def save_settings(self):
'''
Return JSON string with target name and target dump file
'''
return {
'name': self.name,
'dump_file': self.dump_file,
}
def load_settings(self, json):
'''
Load data from dictionary
'''
for item in json:
if item.get('name') == self.name:
self.dump_file = item.get('dump_file')
#===============================================================================
# Database snapshots
#===============================================================================
class Database(BackupTarget):
'''Database snapshot representation'''
connection_settings = {
'dbname': None,
'host': None,
'port': None,
'user': None,
'password': None,
}
encoding = 'UTF-8'
def __init__(self, settings_module):
self.connection_settings['dbname'] = getattr(settings_module, 'DATABASE_NAME')
self.connection_settings['host'] = getattr(settings_module, 'DATABASE_HOST', '127.0.0.1')
self.connection_settings['port'] = getattr(settings_module, 'DATABASE_PORT')
self.connection_settings['user'] = getattr(settings_module, 'DATABASE_USER')
self.connection_settings['password'] = getattr(settings_module, 'DATABASE_PASSWORD')
return super(Database, self).__init__()
class PostgresDatabase(Database):
name = 'postgres'
def _re_create_database(self):
return '\n'.join([
'\connect postgres;',
'DROP DATABASE %s;' % self.connection_settings['dbname'],
"CREATE DATABASE %s WITH OWNER %s ENCODING='%s';" % (
self.connection_settings['dbname'],
self.connection_settings['user'],
self.encoding,
),
'\connect %s;' % self.connection_settings['dbname'],
'',
])
def _authenticate(self):
if 'user' in self.connection_settings:
os.environ['PGUSER'] = self.connection_settings['user']
if 'password' in self.connection_settings:
os.environ['PGPASSWORD'] = self.connection_settings['password']
if 'dbname' in self.connection_settings:
os.environ['PGDATABASE'] = self.connection_settings['dbname']
def snapshot(self):
'''Make a snapshot of database. File in sql format supposed to be written on disk'''
logging.info('Taking a snapshot')
args = []
self._authenticate()
if 'host' in self.connection_settings:
args += ['--host=%s' % self.connection_settings['host']]
if 'port' in self.connection_settings:
args += ['--port=%s' % self.connection_settings['port']]
if self.connection_settings['dbname']:
args += [self.connection_settings['dbname']]
command = 'pg_dump %s' % (' '.join(args))
pipe = Popen(command, shell=True, stdin=PIPE, stdout=PIPE)
(stdout, stderr) = pipe.communicate(self.connection_settings['password'])
if pipe.wait() != 0:
logging.error('Error in database snapshot')
else:
logging.info('Database snapshot finished')
self.dump_file = 'database_postgres_backup.%s.sql' % (
datetime.datetime.now().strftime('%Y-%m-%d_%H-%M'))
file = open(os.path.join(settings.SNAPSHOTS_DIR, self.dump_file), 'w')
# save dump to file
file.write(self._re_create_database())
file.write(stdout)
file.close()
def restore(self):
'''Restore from sql file. Filename should be provided in self.dump_file'''
if not self.dump_file:
logging.error('Restore filename is None. Aborting')
return
logging.info('Restoring from %s' % self.dump_file)
args = []
self._authenticate()
if 'host' in self.connection_settings:
args += ['--host=%s' % self.connection_settings['host']]
if 'port' in self.connection_settings:
args += ['--port=%s' % self.connection_settings['port']]
command = 'psql %s < %s' % (' '.join(args), os.path.join(
self.unpack_path, self.dump_file))
pipe = Popen(command, shell=True, stdin=PIPE, stdout=PIPE)
if pipe.wait() != 0:
logging.error('Error while restoring')
else:
logging.info('Restored successfully')
#===============================================================================
# Directory snapshots
#===============================================================================
class Directory(BackupTarget):
'''File directory backup target'''
# TODO: filemask = ''
backup_dir = None
remove_old_files = True
def __init__(self, backup_dir):
self.backup_dir = backup_dir
return super(Directory, self).__init__()
def snapshot(self):
logging.info('Taking a snapshot')
self.dump_file = 'directory_backup.%s.tar' % (
datetime.datetime.now().strftime('%Y-%m-%d_%H-%M'))
command = 'tar cf %s -C %s .' % (os.path.join(
settings.SNAPSHOTS_DIR, self.dump_file), self.backup_dir)
pipe = Popen(command, shell=True)
if pipe.wait() != 0:
logging.error('Error while snapshot directory')
else:
logging.info('Snapshot directory successfully')
def restore(self):
if not self.dump_file:
logging.error('Restore filename is None. Aborting')
return
logging.info('Restoring from %s' % self.dump_file)
if self.remove_old_files:
rmtree(self.backup_dir)
os.mkdir(self.backup_dir)
command = 'tar xf %s -C %s .' % (os.path.join(self.unpack_path,
self.dump_file), self.backup_dir)
pipe = Popen(command, shell=True)
if pipe.wait() != 0:
logging.error('Error while restoring directory')
else:
logging.info('Directory restored successfully')
class MediaDirectory(Directory):
name = 'media'
def __init__(self, settings_module):
return super(MediaDirectory, self).__init__(settings_module.MEDIA_ROOT)
+class MediaUploadDirectory(Directory):
+ name = 'media_upload'
+ def __init__(self, settings_module):
+ # try import UPLOAD ROOT from settings, fault to 'upload'
+ upload_dir = getattr(settings_module, 'UPLOAD_ROOT', None)
+ if not upload_dir:
+ upload_dir = os.path.join(settings_module.MEDIA_ROOT, 'upload')
+ return super(MediaUploadDirectory, self).__init__(upload_dir)
+
+
#===============================================================================
# Collating objects class
#===============================================================================
class SnapSite(object):
'''A Django site snapshot
Attributes:
media - path to media directory
database - dictionary with database settings
settings - imported settings module from the site
'''
targets = []
def __init__(self, arg_settings=None):
if arg_settings:
django_settings = arg_settings
else:
from django.conf import settings
django_settings = settings
# get targets
for target_classname in SNAPSHOT_TARGETS:
Target = import_item(target_classname)
self.targets.append(Target(django_settings))
# create snapshots folder if not exists
if not os.path.exists(SNAPSHOTS_DIR):
os.mkdir(SNAPSHOTS_DIR)
return super(SnapSite, self).__init__()
def snapshot(self):
for target in self.targets:
target.snapshot()
# save settings to file
json_file = open(os.path.join(SNAPSHOTS_DIR, 'info.json'), 'w')
json_file.write(simplejson.dumps(
[target.save_settings() for target in self.targets],
indent=4,
))
json_file.close()
# and gzip contents to snapshot
archive_name = 'snapshot.%s.tar.gz' % (datetime.datetime.now().strftime('%Y-%m-%d_%H-%M'))
command = 'tar czf %(archive_name)s --remove-files -C %(path)s %(files)s ' % ({
'archive_name': os.path.join(SNAPSHOTS_DIR, archive_name),
'path': SNAPSHOTS_DIR,
'files': ' '.join([target.dump_file for target in self.targets] + ['info.json']),
})
pipe = Popen(command, shell=True)
if pipe.wait() != 0:
logging.error('Error while snapshot')
else:
logging.info('Snapshot successfully')
def restore(self, filename):
# first, unpack snapshot to temporary directory
unpack_path = os.path.join(SNAPSHOTS_DIR, 'tmp')
# delete old tmp directory if exixsts
if os.path.exists(unpack_path):
rmtree(unpack_path)
os.mkdir(unpack_path)
pipe = Popen('tar xf %s -C %s' % (os.path.join(SNAPSHOTS_DIR,
filename), unpack_path), shell=True)
pipe.wait()
# read settings from file
json_settings_file = open(os.path.join(SNAPSHOTS_DIR, 'tmp/info.json'), 'r')
json_settings = simplejson.loads(json_settings_file.read())
# load settings into target instances
for target in self.targets:
target.unpack_path = unpack_path
target.load_settings(json_settings)
# restore
for target in self.targets:
target.restore()
# remove tmp dir
rmtree(unpack_path)
diff --git a/snapshot/settings.py b/snapshot/settings.py
index 753bfb6..e158119 100644
--- a/snapshot/settings.py
+++ b/snapshot/settings.py
@@ -1,11 +1,11 @@
# -*- coding: utf-8 -*-
from django.conf import settings as project_settings
from os.path import join, dirname
SNAPSHOTS_DIR = getattr(project_settings, 'SNAPSHOTS_DIR',
join(dirname(project_settings.MEDIA_ROOT), 'snapshots'))
SNAPSHOT_TARGETS = getattr(project_settings, 'SNAPSHOT_TARGETS', [
- 'snapshot.models.MediaDirectory',
+ 'snapshot.models.MediaUploadDirectory',
'snapshot.models.PostgresDatabase',
])
|
redsolution/django-snapshot
|
4dde424e5e06819ea6b0fecb2a1398989fd511a0
|
Targets are in separate setting now
|
diff --git a/snapshot/models.py b/snapshot/models.py
index b6072d2..a425fd7 100644
--- a/snapshot/models.py
+++ b/snapshot/models.py
@@ -1,285 +1,287 @@
# -*- coding: utf-8 -*-
from django.utils import simplejson
from shutil import rmtree
from snapshot import settings
from subprocess import Popen, PIPE, call
+from snapshot.settings import SNAPSHOT_TARGETS, SNAPSHOTS_DIR
+from snapshot.utils import import_item
import datetime
import logging
import os
import sys
logging.getLogger().setLevel(logging.DEBUG)
class MustOverride(Exception):
pass
class BackupTarget(object):
'''Class for main targets to backup and restore
It supposed to be overriden by database and filesystem extensions
'''
name = 'backup_target'
dump_file = None
unpack_path = ''
def snapshot(self):
raise MustOverride
def restore(self, dump):
raise MustOverride
def save_settings(self):
'''
Return JSON string with target name and target dump file
'''
return {
'name': self.name,
'dump_file': self.dump_file,
}
def load_settings(self, json):
'''
Load data from dictionary
'''
for item in json:
if item.get('name') == self.name:
self.dump_file = item.get('dump_file')
#===============================================================================
# Database snapshots
#===============================================================================
class Database(BackupTarget):
'''Database snapshot representation'''
connection_settings = {
'dbname': None,
'host': None,
'port': None,
'user': None,
'password': None,
}
encoding = 'UTF-8'
def __init__(self, settings_module):
self.connection_settings['dbname'] = getattr(settings_module, 'DATABASE_NAME')
self.connection_settings['host'] = getattr(settings_module, 'DATABASE_HOST', '127.0.0.1')
self.connection_settings['port'] = getattr(settings_module, 'DATABASE_PORT')
self.connection_settings['user'] = getattr(settings_module, 'DATABASE_USER')
self.connection_settings['password'] = getattr(settings_module, 'DATABASE_PASSWORD')
return super(Database, self).__init__()
class PostgresDatabase(Database):
name = 'postgres'
def _re_create_database(self):
return '\n'.join([
'\connect postgres;',
'DROP DATABASE %s;' % self.connection_settings['dbname'],
"CREATE DATABASE %s WITH OWNER %s ENCODING='%s';" % (
self.connection_settings['dbname'],
self.connection_settings['user'],
self.encoding,
),
'\connect %s;' % self.connection_settings['dbname'],
'',
])
def _authenticate(self):
if 'user' in self.connection_settings:
os.environ['PGUSER'] = self.connection_settings['user']
if 'password' in self.connection_settings:
os.environ['PGPASSWORD'] = self.connection_settings['password']
if 'dbname' in self.connection_settings:
os.environ['PGDATABASE'] = self.connection_settings['dbname']
def snapshot(self):
'''Make a snapshot of database. File in sql format supposed to be written on disk'''
logging.info('Taking a snapshot')
args = []
self._authenticate()
if 'host' in self.connection_settings:
args += ['--host=%s' % self.connection_settings['host']]
if 'port' in self.connection_settings:
args += ['--port=%s' % self.connection_settings['port']]
if self.connection_settings['dbname']:
args += [self.connection_settings['dbname']]
command = 'pg_dump %s' % (' '.join(args))
pipe = Popen(command, shell=True, stdin=PIPE, stdout=PIPE)
(stdout, stderr) = pipe.communicate(self.connection_settings['password'])
if pipe.wait() != 0:
logging.error('Error in database snapshot')
else:
logging.info('Database snapshot finished')
self.dump_file = 'database_postgres_backup.%s.sql' % (
datetime.datetime.now().strftime('%Y-%m-%d_%H-%M'))
file = open(os.path.join(settings.SNAPSHOTS_DIR, self.dump_file), 'w')
# save dump to file
file.write(self._re_create_database())
file.write(stdout)
file.close()
def restore(self):
'''Restore from sql file. Filename should be provided in self.dump_file'''
if not self.dump_file:
logging.error('Restore filename is None. Aborting')
return
logging.info('Restoring from %s' % self.dump_file)
args = []
self._authenticate()
if 'host' in self.connection_settings:
args += ['--host=%s' % self.connection_settings['host']]
if 'port' in self.connection_settings:
args += ['--port=%s' % self.connection_settings['port']]
command = 'psql %s < %s' % (' '.join(args), os.path.join(
self.unpack_path, self.dump_file))
pipe = Popen(command, shell=True, stdin=PIPE, stdout=PIPE)
if pipe.wait() != 0:
logging.error('Error while restoring')
else:
logging.info('Restored successfully')
#===============================================================================
# Directory snapshots
#===============================================================================
class Directory(BackupTarget):
'''File directory backup target'''
# TODO: filemask = ''
backup_dir = None
remove_old_files = True
def __init__(self, backup_dir):
self.backup_dir = backup_dir
return super(Directory, self).__init__()
def snapshot(self):
logging.info('Taking a snapshot')
self.dump_file = 'directory_backup.%s.tar' % (
datetime.datetime.now().strftime('%Y-%m-%d_%H-%M'))
command = 'tar cf %s -C %s .' % (os.path.join(
settings.SNAPSHOTS_DIR, self.dump_file), self.backup_dir)
pipe = Popen(command, shell=True)
if pipe.wait() != 0:
logging.error('Error while snapshot directory')
else:
logging.info('Snapshot directory successfully')
def restore(self):
if not self.dump_file:
logging.error('Restore filename is None. Aborting')
return
logging.info('Restoring from %s' % self.dump_file)
if self.remove_old_files:
rmtree(self.backup_dir)
os.mkdir(self.backup_dir)
command = 'tar xf %s -C %s .' % (os.path.join(self.unpack_path,
self.dump_file), self.backup_dir)
pipe = Popen(command, shell=True)
if pipe.wait() != 0:
logging.error('Error while restoring directory')
else:
- logging.info('Directory restored successfully ')
+ logging.info('Directory restored successfully')
class MediaDirectory(Directory):
name = 'media'
def __init__(self, settings_module):
return super(MediaDirectory, self).__init__(settings_module.MEDIA_ROOT)
#===============================================================================
# Collating objects class
#===============================================================================
class SnapSite(object):
'''A Django site snapshot
Attributes:
media - path to media directory
database - dictionary with database settings
settings - imported settings module from the site
'''
- media = None
- database = None
+ targets = []
def __init__(self, arg_settings=None):
if arg_settings:
django_settings = arg_settings
else:
from django.conf import settings
django_settings = settings
- self.media = MediaDirectory(django_settings)
- self.database = PostgresDatabase(django_settings)
+ # get targets
+ for target_classname in SNAPSHOT_TARGETS:
+ Target = import_item(target_classname)
+ self.targets.append(Target(django_settings))
+
# create snapshots folder if not exists
- from snapshot import settings
- if not os.path.exists(settings.SNAPSHOTS_DIR):
- os.mkdir(settings.SNAPSHOTS_DIR)
+ if not os.path.exists(SNAPSHOTS_DIR):
+ os.mkdir(SNAPSHOTS_DIR)
return super(SnapSite, self).__init__()
def snapshot(self):
- self.database.snapshot()
- self.media.snapshot()
+ for target in self.targets:
+ target.snapshot()
# save settings to file
- json_file = open(os.path.join(settings.SNAPSHOTS_DIR, 'info.json'), 'w')
+ json_file = open(os.path.join(SNAPSHOTS_DIR, 'info.json'), 'w')
json_file.write(simplejson.dumps(
- [self.database.save_settings(), self.media.save_settings()],
+ [target.save_settings() for target in self.targets],
indent=4,
))
json_file.close()
# and gzip contents to snapshot
archive_name = 'snapshot.%s.tar.gz' % (datetime.datetime.now().strftime('%Y-%m-%d_%H-%M'))
command = 'tar czf %(archive_name)s --remove-files -C %(path)s %(files)s ' % ({
- 'archive_name': os.path.join(settings.SNAPSHOTS_DIR, archive_name),
- 'path': settings.SNAPSHOTS_DIR,
- 'files': ' '.join([self.database.dump_file, self.media.dump_file, 'info.json']),
+ 'archive_name': os.path.join(SNAPSHOTS_DIR, archive_name),
+ 'path': SNAPSHOTS_DIR,
+ 'files': ' '.join([target.dump_file for target in self.targets] + ['info.json']),
})
pipe = Popen(command, shell=True)
if pipe.wait() != 0:
logging.error('Error while snapshot')
else:
logging.info('Snapshot successfully')
def restore(self, filename):
# first, unpack snapshot to temporary directory
- unpack_path = os.path.join(settings.SNAPSHOTS_DIR, 'tmp')
+ unpack_path = os.path.join(SNAPSHOTS_DIR, 'tmp')
# delete old tmp directory if exixsts
if os.path.exists(unpack_path):
rmtree(unpack_path)
os.mkdir(unpack_path)
- pipe = Popen('tar xf %s -C %s' % (os.path.join(settings.SNAPSHOTS_DIR,
+ pipe = Popen('tar xf %s -C %s' % (os.path.join(SNAPSHOTS_DIR,
filename), unpack_path), shell=True)
pipe.wait()
# read settings from file
- json_settings_file = open(os.path.join(settings.SNAPSHOTS_DIR, 'tmp/info.json'), 'r')
+ json_settings_file = open(os.path.join(SNAPSHOTS_DIR, 'tmp/info.json'), 'r')
json_settings = simplejson.loads(json_settings_file.read())
# load settings into target instances
- self.database.unpack_path = unpack_path
- self.media.unpack_path = unpack_path
- self.database.load_settings(json_settings)
- self.media.load_settings(json_settings)
+ for target in self.targets:
+ target.unpack_path = unpack_path
+ target.load_settings(json_settings)
# restore
- self.media.restore()
- self.database.restore()
+ for target in self.targets:
+ target.restore()
# remove tmp dir
rmtree(unpack_path)
diff --git a/snapshot/settings.py b/snapshot/settings.py
index d9cfe97..753bfb6 100644
--- a/snapshot/settings.py
+++ b/snapshot/settings.py
@@ -1,6 +1,11 @@
# -*- coding: utf-8 -*-
from django.conf import settings as project_settings
from os.path import join, dirname
SNAPSHOTS_DIR = getattr(project_settings, 'SNAPSHOTS_DIR',
join(dirname(project_settings.MEDIA_ROOT), 'snapshots'))
+
+SNAPSHOT_TARGETS = getattr(project_settings, 'SNAPSHOT_TARGETS', [
+ 'snapshot.models.MediaDirectory',
+ 'snapshot.models.PostgresDatabase',
+])
diff --git a/snapshot/utils.py b/snapshot/utils.py
new file mode 100644
index 0000000..8f9cc7c
--- /dev/null
+++ b/snapshot/utils.py
@@ -0,0 +1,9 @@
+
+def import_item(path):
+ """Imports a model by given string. In error case raises ImpoprelyConfigured"""
+ i = path.rfind('.')
+ module, attr = path[:i], path[i + 1:]
+ try:
+ return getattr(__import__(module, {}, {}, ['']), attr)
+ except ImportError, e:
+ raise ImproperlyConfigured('Error importing %s: "%s"' % (path, e))
|
redsolution/django-snapshot
|
f3bd0d31edbb395613b7e04591de6d419604e557
|
Catched some exceptions
|
diff --git a/snapshot/management/commands/snap.py b/snapshot/management/commands/snap.py
index 1ad8516..cfe25e9 100644
--- a/snapshot/management/commands/snap.py
+++ b/snapshot/management/commands/snap.py
@@ -1,49 +1,55 @@
# -*- coding: utf-8 -*-
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from optparse import OptionParser
from snapshot.models import SnapSite
from snapshot import settings as snapshot_settings
import os
class Command(BaseCommand):
help = '''Usage:
snap save - take a snapshot at current time
snap restore [i] - restore from [i] snapshot (0 by default)
snap list - list all available snapshots
'''
def handle(self, *args, **options):
if args:
action = args[0]
else:
action = None
# TODO: check settings directory
if action == 'save':
site = SnapSite(settings)
site.snapshot()
elif action == 'restore':
if len(args) > 1:
try:
number = int(args[1])
except ValueError:
raise CommandError('restre second argument must be digit')
else:
number = 0
- snapshots = os.listdir(snapshot_settings.SNAPSHOTS_DIR)
try:
+ snapshots = os.listdir(snapshot_settings.SNAPSHOTS_DIR)
+ snapshots = sorted(snapshots)
snapshot_filename = snapshots[number]
except IndexError:
raise CommandError('Incorrect snapshot number')
+ except OSError:
+ raise CommandError("Snapshots wasn't created")
+
site = SnapSite(settings)
site.restore(snapshot_filename)
elif action == 'list':
- snapshots = os.listdir(snapshot_settings.SNAPSHOTS_DIR)
+ try:
+ snapshots = os.listdir(snapshot_settings.SNAPSHOTS_DIR)
+ snapshots = sorted(snapshots)
+ except OSError:
+ raise CommandError("Snapshots wasn't created")
for i in range(len(snapshots)):
print '%d: %s' % (i, snapshots[i])
else:
print self.help
-
-
|
redsolution/django-snapshot
|
42825033ff8d43cbdb0323bbb2c0fdb52b121464
|
Added snapshots folder auto-creation
|
diff --git a/snapshot/models.py b/snapshot/models.py
index c47365c..b6072d2 100644
--- a/snapshot/models.py
+++ b/snapshot/models.py
@@ -1,280 +1,285 @@
# -*- coding: utf-8 -*-
from django.utils import simplejson
from shutil import rmtree
from snapshot import settings
from subprocess import Popen, PIPE, call
import datetime
import logging
import os
import sys
logging.getLogger().setLevel(logging.DEBUG)
class MustOverride(Exception):
pass
class BackupTarget(object):
'''Class for main targets to backup and restore
It supposed to be overriden by database and filesystem extensions
'''
name = 'backup_target'
dump_file = None
unpack_path = ''
def snapshot(self):
raise MustOverride
def restore(self, dump):
raise MustOverride
def save_settings(self):
'''
Return JSON string with target name and target dump file
'''
return {
'name': self.name,
'dump_file': self.dump_file,
}
def load_settings(self, json):
'''
Load data from dictionary
'''
for item in json:
if item.get('name') == self.name:
self.dump_file = item.get('dump_file')
#===============================================================================
# Database snapshots
#===============================================================================
class Database(BackupTarget):
'''Database snapshot representation'''
connection_settings = {
'dbname': None,
'host': None,
'port': None,
'user': None,
'password': None,
}
encoding = 'UTF-8'
def __init__(self, settings_module):
self.connection_settings['dbname'] = getattr(settings_module, 'DATABASE_NAME')
self.connection_settings['host'] = getattr(settings_module, 'DATABASE_HOST', '127.0.0.1')
self.connection_settings['port'] = getattr(settings_module, 'DATABASE_PORT')
self.connection_settings['user'] = getattr(settings_module, 'DATABASE_USER')
self.connection_settings['password'] = getattr(settings_module, 'DATABASE_PASSWORD')
return super(Database, self).__init__()
class PostgresDatabase(Database):
name = 'postgres'
def _re_create_database(self):
return '\n'.join([
'\connect postgres;',
'DROP DATABASE %s;' % self.connection_settings['dbname'],
"CREATE DATABASE %s WITH OWNER %s ENCODING='%s';" % (
self.connection_settings['dbname'],
self.connection_settings['user'],
self.encoding,
),
'\connect %s;' % self.connection_settings['dbname'],
'',
])
def _authenticate(self):
if 'user' in self.connection_settings:
os.environ['PGUSER'] = self.connection_settings['user']
if 'password' in self.connection_settings:
os.environ['PGPASSWORD'] = self.connection_settings['password']
if 'dbname' in self.connection_settings:
os.environ['PGDATABASE'] = self.connection_settings['dbname']
def snapshot(self):
'''Make a snapshot of database. File in sql format supposed to be written on disk'''
logging.info('Taking a snapshot')
args = []
self._authenticate()
if 'host' in self.connection_settings:
args += ['--host=%s' % self.connection_settings['host']]
if 'port' in self.connection_settings:
args += ['--port=%s' % self.connection_settings['port']]
if self.connection_settings['dbname']:
args += [self.connection_settings['dbname']]
command = 'pg_dump %s' % (' '.join(args))
pipe = Popen(command, shell=True, stdin=PIPE, stdout=PIPE)
(stdout, stderr) = pipe.communicate(self.connection_settings['password'])
if pipe.wait() != 0:
logging.error('Error in database snapshot')
else:
logging.info('Database snapshot finished')
self.dump_file = 'database_postgres_backup.%s.sql' % (
datetime.datetime.now().strftime('%Y-%m-%d_%H-%M'))
file = open(os.path.join(settings.SNAPSHOTS_DIR, self.dump_file), 'w')
# save dump to file
file.write(self._re_create_database())
file.write(stdout)
file.close()
def restore(self):
'''Restore from sql file. Filename should be provided in self.dump_file'''
if not self.dump_file:
logging.error('Restore filename is None. Aborting')
return
logging.info('Restoring from %s' % self.dump_file)
args = []
self._authenticate()
if 'host' in self.connection_settings:
args += ['--host=%s' % self.connection_settings['host']]
if 'port' in self.connection_settings:
args += ['--port=%s' % self.connection_settings['port']]
command = 'psql %s < %s' % (' '.join(args), os.path.join(
self.unpack_path, self.dump_file))
pipe = Popen(command, shell=True, stdin=PIPE, stdout=PIPE)
if pipe.wait() != 0:
logging.error('Error while restoring')
else:
logging.info('Restored successfully')
#===============================================================================
# Directory snapshots
#===============================================================================
class Directory(BackupTarget):
'''File directory backup target'''
# TODO: filemask = ''
backup_dir = None
remove_old_files = True
def __init__(self, backup_dir):
self.backup_dir = backup_dir
return super(Directory, self).__init__()
def snapshot(self):
logging.info('Taking a snapshot')
self.dump_file = 'directory_backup.%s.tar' % (
datetime.datetime.now().strftime('%Y-%m-%d_%H-%M'))
command = 'tar cf %s -C %s .' % (os.path.join(
settings.SNAPSHOTS_DIR, self.dump_file), self.backup_dir)
pipe = Popen(command, shell=True)
if pipe.wait() != 0:
logging.error('Error while snapshot directory')
else:
logging.info('Snapshot directory successfully')
def restore(self):
if not self.dump_file:
logging.error('Restore filename is None. Aborting')
return
logging.info('Restoring from %s' % self.dump_file)
if self.remove_old_files:
rmtree(self.backup_dir)
os.mkdir(self.backup_dir)
command = 'tar xf %s -C %s .' % (os.path.join(self.unpack_path,
self.dump_file), self.backup_dir)
pipe = Popen(command, shell=True)
if pipe.wait() != 0:
logging.error('Error while restoring directory')
else:
logging.info('Directory restored successfully ')
class MediaDirectory(Directory):
name = 'media'
def __init__(self, settings_module):
return super(MediaDirectory, self).__init__(settings_module.MEDIA_ROOT)
#===============================================================================
# Collating objects class
#===============================================================================
class SnapSite(object):
'''A Django site snapshot
Attributes:
media - path to media directory
database - dictionary with database settings
settings - imported settings module from the site
'''
- settings = None
media = None
database = None
- def __init__(self, settings=None):
- if settings:
- self.settings = settings
+ def __init__(self, arg_settings=None):
+ if arg_settings:
+ django_settings = arg_settings
else:
from django.conf import settings
- self.media = MediaDirectory(settings)
- self.database = PostgresDatabase(settings)
+ django_settings = settings
+
+ self.media = MediaDirectory(django_settings)
+ self.database = PostgresDatabase(django_settings)
+ # create snapshots folder if not exists
+ from snapshot import settings
+ if not os.path.exists(settings.SNAPSHOTS_DIR):
+ os.mkdir(settings.SNAPSHOTS_DIR)
return super(SnapSite, self).__init__()
def snapshot(self):
self.database.snapshot()
self.media.snapshot()
# save settings to file
json_file = open(os.path.join(settings.SNAPSHOTS_DIR, 'info.json'), 'w')
json_file.write(simplejson.dumps(
[self.database.save_settings(), self.media.save_settings()],
indent=4,
))
json_file.close()
# and gzip contents to snapshot
archive_name = 'snapshot.%s.tar.gz' % (datetime.datetime.now().strftime('%Y-%m-%d_%H-%M'))
command = 'tar czf %(archive_name)s --remove-files -C %(path)s %(files)s ' % ({
'archive_name': os.path.join(settings.SNAPSHOTS_DIR, archive_name),
'path': settings.SNAPSHOTS_DIR,
'files': ' '.join([self.database.dump_file, self.media.dump_file, 'info.json']),
})
pipe = Popen(command, shell=True)
if pipe.wait() != 0:
logging.error('Error while snapshot')
else:
logging.info('Snapshot successfully')
def restore(self, filename):
# first, unpack snapshot to temporary directory
unpack_path = os.path.join(settings.SNAPSHOTS_DIR, 'tmp')
# delete old tmp directory if exixsts
if os.path.exists(unpack_path):
rmtree(unpack_path)
os.mkdir(unpack_path)
pipe = Popen('tar xf %s -C %s' % (os.path.join(settings.SNAPSHOTS_DIR,
filename), unpack_path), shell=True)
pipe.wait()
# read settings from file
json_settings_file = open(os.path.join(settings.SNAPSHOTS_DIR, 'tmp/info.json'), 'r')
json_settings = simplejson.loads(json_settings_file.read())
# load settings into target instances
self.database.unpack_path = unpack_path
self.media.unpack_path = unpack_path
self.database.load_settings(json_settings)
self.media.load_settings(json_settings)
# restore
self.media.restore()
self.database.restore()
# remove tmp dir
rmtree(unpack_path)
|
redsolution/django-snapshot
|
d1e83059647f7846bc242aaebc2dc9b581b652b1
|
simple snapshots with tar and pg_dump
|
diff --git a/snapshot/management/commands/snap.py b/snapshot/management/commands/snap.py
new file mode 100644
index 0000000..1ad8516
--- /dev/null
+++ b/snapshot/management/commands/snap.py
@@ -0,0 +1,49 @@
+# -*- coding: utf-8 -*-
+from django.conf import settings
+from django.core.management.base import BaseCommand, CommandError
+from optparse import OptionParser
+from snapshot.models import SnapSite
+from snapshot import settings as snapshot_settings
+import os
+
+class Command(BaseCommand):
+ help = '''Usage:
+ snap save - take a snapshot at current time
+ snap restore [i] - restore from [i] snapshot (0 by default)
+ snap list - list all available snapshots
+ '''
+
+ def handle(self, *args, **options):
+ if args:
+ action = args[0]
+ else:
+ action = None
+
+ # TODO: check settings directory
+ if action == 'save':
+ site = SnapSite(settings)
+ site.snapshot()
+ elif action == 'restore':
+ if len(args) > 1:
+ try:
+ number = int(args[1])
+ except ValueError:
+ raise CommandError('restre second argument must be digit')
+ else:
+ number = 0
+
+ snapshots = os.listdir(snapshot_settings.SNAPSHOTS_DIR)
+ try:
+ snapshot_filename = snapshots[number]
+ except IndexError:
+ raise CommandError('Incorrect snapshot number')
+ site = SnapSite(settings)
+ site.restore(snapshot_filename)
+ elif action == 'list':
+ snapshots = os.listdir(snapshot_settings.SNAPSHOTS_DIR)
+ for i in range(len(snapshots)):
+ print '%d: %s' % (i, snapshots[i])
+ else:
+ print self.help
+
+
diff --git a/snapshot/management/commands/snapshot.py b/snapshot/management/commands/snapshot.py
deleted file mode 100644
index 08fc79d..0000000
--- a/snapshot/management/commands/snapshot.py
+++ /dev/null
@@ -1,19 +0,0 @@
-# -*- coding: utf-8 -*-
-from optparse import OptionParser
-from django.core.management.base import BaseCommand, CommandError
-from django.conf import settings
-from snapshot.models import SnapSite
-
-class Command(BaseCommand):
- help = '''TODO: Usage description
- '''
-
- def handle(self, *args, **options):
- if args:
- action = args[0]
- else:
- action = None
-
- # TODO: check settings directory
- if action == 'save':
- site = SnapSite(settings)
diff --git a/snapshot/models.py b/snapshot/models.py
index 8f42c1e..c47365c 100644
--- a/snapshot/models.py
+++ b/snapshot/models.py
@@ -1,252 +1,280 @@
# -*- coding: utf-8 -*-
-import os
-import sys
-from optparse import OptionParser
-from subprocess import Popen, PIPE
+from django.utils import simplejson
+from shutil import rmtree
+from snapshot import settings
+from subprocess import Popen, PIPE, call
import datetime
import logging
-import shutil
-from snapshot import settings
-from django.utils import simplejson
+import os
+import sys
+
logging.getLogger().setLevel(logging.DEBUG)
class MustOverride(Exception):
pass
class BackupTarget(object):
'''Class for main targets to backup and restore
It supposed to be overriden by database and filesystem extensions
'''
name = 'backup_target'
dump_file = None
+ unpack_path = ''
def snapshot(self):
raise MustOverride
def restore(self, dump):
raise MustOverride
def save_settings(self):
'''
Return JSON string with target name and target dump file
'''
return {
'name': self.name,
'dump_file': self.dump_file,
}
- def load_settings(self, json_string):
+ def load_settings(self, json):
'''
- Load data from JSON string
+ Load data from dictionary
'''
- json = simplejson.loads(json_string)
for item in json:
if item.get('name') == self.name:
self.dump_file = item.get('dump_file')
#===============================================================================
# Database snapshots
#===============================================================================
class Database(BackupTarget):
'''Database snapshot representation'''
connection_settings = {
'dbname': None,
'host': None,
'port': None,
'user': None,
'password': None,
}
encoding = 'UTF-8'
def __init__(self, settings_module):
self.connection_settings['dbname'] = getattr(settings_module, 'DATABASE_NAME')
self.connection_settings['host'] = getattr(settings_module, 'DATABASE_HOST', '127.0.0.1')
self.connection_settings['port'] = getattr(settings_module, 'DATABASE_PORT')
self.connection_settings['user'] = getattr(settings_module, 'DATABASE_USER')
self.connection_settings['password'] = getattr(settings_module, 'DATABASE_PASSWORD')
return super(Database, self).__init__()
class PostgresDatabase(Database):
name = 'postgres'
def _re_create_database(self):
return '\n'.join([
'\connect postgres;',
'DROP DATABASE %s;' % self.connection_settings['dbname'],
"CREATE DATABASE %s WITH OWNER %s ENCODING='%s';" % (
self.connection_settings['dbname'],
self.connection_settings['user'],
self.encoding,
),
'\connect %s;' % self.connection_settings['dbname'],
'',
])
def _authenticate(self):
if 'user' in self.connection_settings:
os.environ['PGUSER'] = self.connection_settings['user']
if 'password' in self.connection_settings:
os.environ['PGPASSWORD'] = self.connection_settings['password']
if 'dbname' in self.connection_settings:
os.environ['PGDATABASE'] = self.connection_settings['dbname']
def snapshot(self):
'''Make a snapshot of database. File in sql format supposed to be written on disk'''
logging.info('Taking a snapshot')
args = []
self._authenticate()
if 'host' in self.connection_settings:
args += ['--host=%s' % self.connection_settings['host']]
if 'port' in self.connection_settings:
args += ['--port=%s' % self.connection_settings['port']]
if self.connection_settings['dbname']:
args += [self.connection_settings['dbname']]
command = 'pg_dump %s' % (' '.join(args))
pipe = Popen(command, shell=True, stdin=PIPE, stdout=PIPE)
(stdout, stderr) = pipe.communicate(self.connection_settings['password'])
if pipe.wait() != 0:
- logging.error('Error in snapshot')
+ logging.error('Error in database snapshot')
else:
- logging.info('Snapshot finished')
+ logging.info('Database snapshot finished')
self.dump_file = 'database_postgres_backup.%s.sql' % (
datetime.datetime.now().strftime('%Y-%m-%d_%H-%M'))
file = open(os.path.join(settings.SNAPSHOTS_DIR, self.dump_file), 'w')
# save dump to file
file.write(self._re_create_database())
file.write(stdout)
file.close()
def restore(self):
'''Restore from sql file. Filename should be provided in self.dump_file'''
if not self.dump_file:
logging.error('Restore filename is None. Aborting')
return
logging.info('Restoring from %s' % self.dump_file)
args = []
self._authenticate()
if 'host' in self.connection_settings:
args += ['--host=%s' % self.connection_settings['host']]
if 'port' in self.connection_settings:
args += ['--port=%s' % self.connection_settings['port']]
command = 'psql %s < %s' % (' '.join(args), os.path.join(
- settings.SNAPSHOTS_DIR, self.dump_file))
+ self.unpack_path, self.dump_file))
pipe = Popen(command, shell=True, stdin=PIPE, stdout=PIPE)
if pipe.wait() != 0:
logging.error('Error while restoring')
else:
logging.info('Restored successfully')
#===============================================================================
# Directory snapshots
#===============================================================================
class Directory(BackupTarget):
'''File directory backup target'''
# TODO: filemask = ''
backup_dir = None
+ remove_old_files = True
def __init__(self, backup_dir):
self.backup_dir = backup_dir
return super(Directory, self).__init__()
def snapshot(self):
logging.info('Taking a snapshot')
self.dump_file = 'directory_backup.%s.tar' % (
datetime.datetime.now().strftime('%Y-%m-%d_%H-%M'))
command = 'tar cf %s -C %s .' % (os.path.join(
settings.SNAPSHOTS_DIR, self.dump_file), self.backup_dir)
pipe = Popen(command, shell=True)
if pipe.wait() != 0:
- logging.error('Error while snapshot')
+ logging.error('Error while snapshot directory')
else:
- logging.info('Snapshot successfully')
+ logging.info('Snapshot directory successfully')
def restore(self):
if not self.dump_file:
logging.error('Restore filename is None. Aborting')
return
logging.info('Restoring from %s' % self.dump_file)
- command = 'tar xf %s -C %s .' % (os.path.join(
- settings.SNAPSHOTS_DIR, self.dump_file), self.backup_dir)
+ if self.remove_old_files:
+ rmtree(self.backup_dir)
+ os.mkdir(self.backup_dir)
+
+ command = 'tar xf %s -C %s .' % (os.path.join(self.unpack_path,
+ self.dump_file), self.backup_dir)
pipe = Popen(command, shell=True)
if pipe.wait() != 0:
- logging.error('Error while restoring')
+ logging.error('Error while restoring directory')
else:
- logging.info('Restored successfully')
+ logging.info('Directory restored successfully ')
class MediaDirectory(Directory):
name = 'media'
def __init__(self, settings_module):
return super(MediaDirectory, self).__init__(settings_module.MEDIA_ROOT)
#===============================================================================
# Collating objects class
#===============================================================================
class SnapSite(object):
'''A Django site snapshot
Attributes:
media - path to media directory
database - dictionary with database settings
settings - imported settings module from the site
'''
settings = None
media = None
database = None
def __init__(self, settings=None):
if settings:
self.settings = settings
else:
from django.conf import settings
self.media = MediaDirectory(settings)
self.database = PostgresDatabase(settings)
return super(SnapSite, self).__init__()
def snapshot(self):
self.database.snapshot()
self.media.snapshot()
# save settings to file
json_file = open(os.path.join(settings.SNAPSHOTS_DIR, 'info.json'), 'w')
json_file.write(simplejson.dumps(
[self.database.save_settings(), self.media.save_settings()],
indent=4,
))
json_file.close()
-
+
# and gzip contents to snapshot
archive_name = 'snapshot.%s.tar.gz' % (datetime.datetime.now().strftime('%Y-%m-%d_%H-%M'))
command = 'tar czf %(archive_name)s --remove-files -C %(path)s %(files)s ' % ({
'archive_name': os.path.join(settings.SNAPSHOTS_DIR, archive_name),
'path': settings.SNAPSHOTS_DIR,
'files': ' '.join([self.database.dump_file, self.media.dump_file, 'info.json']),
})
pipe = Popen(command, shell=True)
if pipe.wait() != 0:
- logging.error('Error while restoring')
+ logging.error('Error while snapshot')
else:
logging.info('Snapshot successfully')
+ def restore(self, filename):
+ # first, unpack snapshot to temporary directory
+ unpack_path = os.path.join(settings.SNAPSHOTS_DIR, 'tmp')
+ # delete old tmp directory if exixsts
+ if os.path.exists(unpack_path):
+ rmtree(unpack_path)
+ os.mkdir(unpack_path)
+ pipe = Popen('tar xf %s -C %s' % (os.path.join(settings.SNAPSHOTS_DIR,
+ filename), unpack_path), shell=True)
+ pipe.wait()
+ # read settings from file
+ json_settings_file = open(os.path.join(settings.SNAPSHOTS_DIR, 'tmp/info.json'), 'r')
+ json_settings = simplejson.loads(json_settings_file.read())
+ # load settings into target instances
+ self.database.unpack_path = unpack_path
+ self.media.unpack_path = unpack_path
+ self.database.load_settings(json_settings)
+ self.media.load_settings(json_settings)
+ # restore
+ self.media.restore()
+ self.database.restore()
+ # remove tmp dir
+ rmtree(unpack_path)
|
dazuiba/fansof
|
3cf9bf959645186fa9261eb660057e1d508b2447
|
finished
|
diff --git a/lib/nanzhou.rb b/lib/nanzhou.rb
index 084c46c..a02946d 100644
--- a/lib/nanzhou.rb
+++ b/lib/nanzhou.rb
@@ -1,160 +1,164 @@
#!/usr/bin/ruby
require 'singleton'
require 'cgi'
require 'rubygems'
require 'patron'
require 'hpricot'
require 'extensions/all'
module ParseModule
attr_reader :doc
def do_request(path)
@doc = new_request(path)
end
def new_request(path)
puts "Request #{path}"
Nanzhou.instance.get_doc(path)
end
def at(path)
doc.at(path)
end
def at_html(path)
at(path).inner_html
end
def at_text(path)
at(path).inner_text
end
def search(path)
doc.search(path)
end
def at_url_pair(path)
a = at(path)
[a['href'], a.inner_html]
end
end
class Journal
URL_BASE = 'enews/infzm/'
PART = {'ç»æµ'=>0, 'è¯è®º'=>1, 'æ°é»'=>2, 'æ¶å±'=>3, '绿è²' =>4 , 'æå'=>5}
include ParseModule
attr_accessor :id, :name, :headline, :parted_content
def initialize(url, name)
url.chomp("/") =~/(\d+)$/
@id = $1.to_i
raise "id #{$1} is not valid" if @id <= 0
@name = name
end
def parse!
do_request(URL_BASE+self.id.to_s)
self.headline = create_content(at(".topnews a"), :head, 0,at_text(".topnews .summary"))
- raise if headline.nil?
- self.parted_content = search(".side-2 h2").map{|e|parse_parts(e, PART[e.inner_text])}
+ raise if headline.nil?
+ self.parted_content = search(".side-2 h2").map{|e|
+ part = PART[e.inner_text]
+ raise "#{e.inner_text} is not exist in #{PART.inspect}" if part.nil?
+ parse_parts(e, part)
+ }
end
def parse_parts(element, part)
next_node = element.next
while next_node&&(next_node = next_node.next).text?
puts "ingore text"
end
next_node.search(".relnews li a").map_with_index do |a, i|
create_content(a, part , i)
end
end
private
def create_content(href_element, part, position_of_part, subtitle=nil)
url, title = href_element['href'], href_element.inner_text
url =~/(\d+)$/
Content.from_hash(:journal=>self, :id => $1,
:part=>part, :position_of_part=>position_of_part,
:title => title, :title2=> subtitle )
end
end
class Content < Struct.new(:journal, :id, :part, :title, :position_of_part, :title2)
URL_BASE = 'content/'
include ParseModule
attr_reader :pages, :author, :publish_at
def self.from_hash(hash)
result = self.new
hash.each{|k,v|result[k]=v}
result
end
def parse!
do_request(URL_BASE+self.id.to_s)
@author = at_text(".relInfo span.author strong")
@publish_at = DateTime.parse(at_text(".relInfo span.pubTime"))
@pages = [at_html("#content-context")]
pages = search("#pageNum .pages a")
if(pages&&pages.pop)
pages.each{|e|
e['href'] =~ /\/(\d+)$/
@pages<< crawl_page($1)
}
end
end
def crawl_page(page_num)
doc = new_request(URL_BASE+self.id.to_s+"/#{page_num}")
doc.at("#content-context").inner_html
end
end
class Nanzhou
include Singleton
def initialize
@session_config = {"Content-Type"=>'application/x-www-form-urlencoded',
"Accept" => "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"User-Agent" => "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2",
"Referer" => "http://www.infzm.com/enews/infzm",
# "Accept-Encoding" => "gzip,deflate",
"Accept-Charset" => "ISO-8859-1,utf-8;q=0.7,*;q=0.7",
"Accept-Language" => "en-us,en;q=0.5",
"Cookie" => %[PHPSESSID=t7ot0hth64p8q0i0sdaallps07; __utma=118487249.973348149.1255276544.1255276544.1255276544.1; __utmb=118487249; __utmc=118487249; __utmz=118487249.1255276544.1.1.utmccn=(organic)|utmcsr=google|utmctr=%E5%8D%97%E6%96%B9%E5%91%A8%E6%9C%AB|utmcmd=organic; OAID=0704d0594d5c9420942f7bb16db28e1f; d041ab46875f9b703c33b8d4c126c757=55+350+3425F+D565E15+A+0+21055504D415E+6+7165A+D+B+2+A46+3+258154550+356555F155D18]
}
@base_url = 'http://www.infzm.com/'
end
def get_doc(path)
doc = Hpricot(session.get(path).body)
end
def parse_journals
content = File.read(File.dirname(__FILE__)+"/index.html.data")
result = Hpricot(content).search("select option").map do |option|
Journal.new(option['value'], option.inner_html)
end
result
end
def session
unless @session
sess = Patron::Session.new
sess.handle_cookies
sess.base_url = @base_url
@session_config.each do |k,v|
sess.headers[k] = v
end
@session = sess
end
@session
end
end
if $0 == __FILE__
js = Nanzhou.instance.parse_journals
j = js.first
j.parse!
j.headline.parse!
end
\ No newline at end of file
|
dazuiba/fansof
|
ff885832e2453fa1ce113175002e83e9e0215691
|
finished
|
diff --git a/lib/c.html.data b/lib/c.html.data
new file mode 100644
index 0000000..c8e2889
--- /dev/null
+++ b/lib/c.html.data
@@ -0,0 +1,509 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+ <title>ÄÏ·½ÖÜÄ© - ¸Ä¸ï¿ª·ÅµÚ¶þ¶¨ÂÉ£ºµÃµÀÕß¶àÖú¡ª¡ª¶ÁÌï¼ÍÔÆ¡¶¸Ä¸ï¿ª·ÅµÄΰ´óʵ¼ù¡·Ö®¶þ</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+ <meta name="keywords" content="ÄÏ·½ÖÜÄ©±¨ ÄÏ·½ÖÜÄ©ÍøÕ¾ ÄÏ·½ÖÜÄ©¹Ù·½ÍøÕ¾ ÄÏ·½ÖÜÄ©µç×Ó°æ ÂÛ̳ ÉçÇø ÔÚÏßÔĶÁ ÐÂÎÅÏßË÷ ¶ÁÕß ¸Ä¸ï¿ª·Å Ìï¼ÍÔÆ ÕþȨ ȨÁ¦" />
+ <meta name="description" content="¶¨ÂÉÄÚÈÝ£ºÎ¥·´µÚÒ»¶¨ÂÉ£¬ÕþȨ¾Í²»Îȶ¨" />
+ <link rel="stylesheet" type="text/css" href="http://images.infzm.com/css/2009/header.css" />
+ <link rel="stylesheet" type="text/css" href="http://images.infzm.com/css/2009/detail_style.css" />
+ <link rel="stylesheet" type="text/css" href="http://images.infzm.com/css/2009/link_default.tabs.css" />
+
+ <link rel="stylesheet" type="text/css" href="http://images.infzm.com/css/2009/footer.css" />
+ <script type="text/javascript" src="http://www.infzm.com/js/mootools-min.js"></script>
+ <script type="text/javascript" src="http://www.infzm.com/2008/js/header.js"></script>
+ <script type="text/javascript" src="http://www.infzm.com/2008/js/detail.js"></script>
+ <script type="text/javascript" src="http://passport.infzm.com/passport/ssologinform/raw?container=userPanel&style=top"></script>
+ <script type="text/javascript" src="http://p.infzm.com/2008/js/moodalbox.v1.2.full.js"></script>
+
+ <script type="text/javascript" src="http://p.infzm.com//2008/js/mootabs1.js"></script>
+
+</head>
+<body>
+ <div id="header">
+<div id="userPanel" class="noUserIcon"></div><!--Óû§×´Ì¬À¸-->
+<div id="left">
+ <a href="http://www.infzm.com" id="siteLogo" title="ÄÏ·½ÖÜÄ©ÍøÕ¾ www.infzm.com"></a>
+ <div id="header-media">
+ <!--top-->
+ <p> </p>
+
+<p><a href="http://www.infzm.com/enews/infzm"><img src="http://images.infzm.com/medias/2009/0930/30820.png" alt="" /><br />
+</a></p> <!--end top -->
+ </div>
+</div>
+<div id="right">
+<h3>ÄÏ·½ÖÜÄ©±¨ÏµÆìÏÂýÌå</h3>
+<a href="http://www.infzm.com/25years.shtml" target="_blank"><div class="nfzm-toplogo"></div></a>
+<a href="http://mangazine.infzm.com" target="_blank"><div class="mangazine-toplogo"></div></a>
+<a href="http://www.infzm.com/enews/nfrwzk" target="_blank"><div class="nfrw-toplogo"></div></a>
+</div>
+ <div class="clear"></div>
+ <div id="NavSearchBar">
+
+ <div id="main-nav"><ul>
+ <li id="home-nav" class=""><a href="http://www.infzm.com">Ê×Ò³</a></li>
+ <li id="blog-nav" class=""><a href="http://www.infzm.com/z.shtml">רÀ¸</a></li>
+<!-- <li id="digg-nav" class=""><a href="http://p.infzm.com">ÍøÕª</a></li>-->
+ <li id="group-nav" class=""><a href="http://group.infzm.com">ÄÏÖÜ´óÔº <font style="color:#c00;font-size:14px">New</font></a></li>
+ <li id="tag-nav" class=""><a href="http://tags.infzm.com">±êÇ©</a></li>
+ <li id="bbs" class=""><a href="http://bbs.infzm.com">ÂÛ̳</a></li>
+ <li id="vote-nav" class=""><a href="http://www.infzm.com/vote.shtml">Ãñµ÷ÖÐÐÄ</a></li>
+
+ <li id="voice"><a href="http://www.infzm.com/voice">ååÓÐÉù</a></li>
+ </ul></div>
+ <div id="search">
+ <span class="tt">ËÑË÷</span>
+ <form method="get" action="http://www.infzm.com/search.php" target="_top" id="SearchForm">
+ <input type="hidden" name="domains" value="infzm.com"></input>
+ <input type="hidden" name="sitesearch" value="infzm.com"></input>
+ <input type="hidden" name="client" value="pub-9592521274658723"></input>
+
+ <input type="hidden" name="forid" value="1"></input>
+ <input type="hidden" name="ie" value="utf-8"></input>
+ <input type="hidden" name="oe" value="utf-8"></input>
+ <input type="hidden" name="cof" value="GALT:#2D8930;GL:1;DIV:#FFFFFF;VLC:CC0000;AH:center;BGC:FFFFFF;LBGC:FFFFFF;ALC:0066CC;LC:0066CC;T:808080;GFNT:99C9FF;GIMP:99C9FF;LH:40;LW:100;L:http://www.infzm.com/images/infzm_logo_0708.gif;S:http://www.infzm.com;LP:1;FORID:11"></input>
+ <input type="hidden" name="hl" value="zh-CN"></input>
+ <span class="input"><input type="text" name="q" value="" /></span>
+ <span class="submit"><input type="image" src="http://www.infzm.com/2008/images/search-submit.png" /></span>
+ </form>
+ </div>
+
+ </div>
+</div> <div id="wrap">
+ <!--CONTENT BEGIN-->
+ <!--Ö÷Ìå-->
+ <div id="contents">
+ <div class="grid_8">
+ <div id="location">
+ <h3>µç×Ó±¨<!--µç×Ó±¨¿¯-->
+
+ >><a href="http://www.infzm.com/enews/infzm">ÄÏ·½ÖÜÄ©</a>>><a href="http://www.infzm.com/enews/infzm/1324">µÚ1338ÆÚ</a></h3>
+ </div>
+ <div id="detailContent">
+ <h1>¸Ä¸ï¿ª·ÅµÚ¶þ¶¨ÂÉ£ºµÃµÀÕß¶àÖú<br/>¡ª¡ª¶ÁÌï¼ÍÔÆ¡¶¸Ä¸ï¿ª·ÅµÄΰ´óʵ¼ù¡·Ö®¶þ</h1>
+ <p class="relInfo">
+ <span class="author">
+ <em>×÷Õß:</em>
+
+ <strong>Îâ˼</strong>
+ </span>
+ <span class="pubTime">2009-09-30 21:53:30</span>
+ <span class="source"><em>À´Ô´:</em>ÄÏ·½ÖÜÄ©</span>
+ </p>
+ <div class="contents">
+ <div id="content-context"><p><q style="quotes: none; font-style: normal; font-weight: bold; font-size: 1em; line-height: 1.5em; color: rgb(0, 85, 170);">¶¨ÂÉÄÚÈÝ£ºÎ¥·´µÚÒ»¶¨ÂÉ£¬ÕþȨ¾Í²»Îȶ¨</q></p>
+
+<p style="text-align: center;"><img width="286" height="400" src="http://images.infzm.com/medias/2009/0930/30811.jpeg" alt="" /></p>
+<p style="text-align: center; font-size: 1em;">¡¶Öйú¾¼ÃµÄ³¤ÆÚ±íÏÖ£º¹«Ôª960-2030Äê¡·£¬£ÛÓ¢£Ý°²¸ñ˹·ÂóµÏÉÖø£¬ÎéÏþÓ¥¡¢ÂíµÂ±óÒ룬ÉϺ£ÈËÃñ³ö°æÉç2008</p>
+<p style="text-align: center;"><img width="292" height="400" src="http://images.infzm.com/medias/2009/0930/30812.jpeg" alt="" /></p>
+<p style="text-align: center; font-size: 1em;">¡¶Ã«Ôó¶«Ñ¡¼¯¡·µÚÎå¾í£¬ÈËÃñ³ö°æÉ磬1977</p>
+<p style="text-align: center;"><img width="282" height="400" src="http://images.infzm.com/medias/2009/0930/30813.jpeg" alt="" /></p>
+<p style="text-align: center; font-size: 1em;">¡¶µË×Ó»Ö´«¡·£¬ÈËÃñ³ö°æÉ磬2006</p>
+<p style="text-align: center;"><img width="278" height="400" src="http://images.infzm.com/medias/2009/0930/30814.jpeg" alt="" /></p>
+<p style="text-align: center; font-size: 1em;">¡¶ÖйúÅ©´åÌåÖÆ±ä¸ïÖØ´ó¾ö²ß¼Íʵ¡·£¬¶ÅÈóÉúÖø£¬ÈËÃñ³ö°æÉ磬2005</p>
+<p style="text-align: center;"><img width="500" height="347" src="http://images.infzm.com/medias/2009/0930/30810.jpeg" alt="" /></p>
+<p style="text-align: center; font-size: 1em;">µËСƽ˵£º“²»¸Ä¸ï¿ª·Å£¬²»·¢Õ¹¾¼Ã£¬²»¸ÄÉÆÈËÃñÉú»î£¬Ö»ÄÜÊÇËÀ·һÌõ¡£”·´¹ýÀ´£¬Ë³Ó¦×ÔÓɶ¨ÂÉ£¬ÓÐÖúÓÚÖ´ÕþÕߵõ½ÃñÖÚµÄÓµ´÷¡£Í¼Îª1984Äê10ÔÂ1ÈÕ,Ìì°²ÃÅǰ¹úÇìÓÎÐжÓÎéÖУ¬Ñ§Éú´ò³öºá·ù“СƽÄúºÃ£¡” ¡¡Í¼/CFP</p>
+
+<p><b>1.µÚÒ»¶¨ÂÉÓëÕþȨÐËÍö</b></p>
+<p>1992Ä꣬Ìï¼ÍÔÆÔÚÖÐÑ뵳У½²»°£¬×ܽáÁËËÕÁª¶«Å·Ö´Õþµ³¿ą̊µÄ½Ìѵ¡£Ëû˵£º“ËÕÁªµÄ¿ą̊£¬¾ø²»ÄÜÖ»°ÑËüÊÓΪһÁ½¸öÈ˵ĴíÎóÔì³ÉµÄ£¬Õâ·½ÃæµÄÔÒòµ±È»ÊÇÖØÒªµÄ£¬µ«×î¸ù±¾µÄÔÒòÊÇËüÄǸöģʽµÄÉç»áÖ÷ÒåûÓÐÄÜ´´Ôì³ö±È×ʱ¾Ö÷Òå¸ü¸ßµÄÉú²úÁ¦·¢Õ¹Ë®Æ½£¬Ã»ÓиøÈËÃñ´øÀ´ÐÒ¸££¬Ê§È¥Á˹ã´óÈËÃñµÄÖ§³Ö¡£Èç¹û˵ËÕÁªµÄ¿ą̊ÊÇÓÉÓÚ³öÁ˸ö¸ê¶û°ÍÇÇ·ò£¬ÄÇôÂÞÂíÄáÑÇ¡¢°¢¶û°ÍÄáÑDz¢Ã»Óиê¶û°ÍÇÇ·ò£¬ÎªÊ²Ã´Ò²¿åÌ¨ÄØ£¿¶«µÂµÄ°ºÄÉ¿ËÊǸöÂí¿Ë˼Ö÷ÒåÕߣ¬¶«µÂ²»Ò²ÊǰØÁÖǽһ²ð¾Í¿ą̊ÁËÂ𣿔</p>
+<p>2002Ä꣬ÔÚ¡¶¸Ä¸ï¿ª·ÅµÄΰ´óʵ¼ù¡·Ò»ÎÄÖУ¬Ìï¼ÍÔÆÓÖÒýÓÃÁ˶íÂÞ˹×ÜͳÆÕ¾©ÔÚ1999Äê12ÔÂÔÚ¡¶Ç§ÄêÖ®½»µÄ¶íÂÞ˹¡·ÖеÄ˵·¨¡£ÆÕ¾©Ëµ£º“ËÕά°£ÕþȨûÓÐʹ¹ú¼Ò·±ÈÙ£¬Éç»á²ýÊ¢£¬ÈËÃñ×ÔÓÉ¡£¾¼ÃµÄÒâʶÐÎ̬»¯µ¼ÖÂÎÒ¹úÔ¶Ô¶ÂäºóÓÚ·¢´ï¹ú¼Ò¡£ÎÞÂÛ³ÐÈÏÕâÒ»µãÓжàôʹ¿à£¬µ«ÊÇÎÒÃǽ«½ü70Äê¶¼ÔÚ×ßÒ»ÌõËÀºúͬ£¬Æ«ÀëÁËÈËÀàµÄ¿µ×¯´óµÀ¡£”</p>
+<p>ʲôÊÇËÀºúͬ£¬Ê²Ã´ÊÇ¿µ×¯´óµÀ£¿Ìï¼ÍÔÆÐ´µÀ£ºµËСƽ¹ØÓÚÊг¡¾¼ÃµÄÀíÂÛ“Ö¸ÒýÎÒÃÇ×ß³ö½©»¯µÄ¼Æ»®¾¼ÃµÄËÀºúͬ£¬ÂõÏòÁË·ûºÏÈËÀàÉç»á¾¼Ã·¢Õ¹¹æÂɵÄÉú»ú²ª²ªµÄÊг¡¾¼ÃµÄ¿µ×¯´óµÀ¡£”Ëæºó£¬Ìï¼ÍÔÆÓÖ½«¾¼ÃµÄÒâʶÐÎ̬»¯£¬½«Ò»´ó¶þ¹«µÄÉç»áÖ÷Ò壬ÓëÍöµ³Íö¹úÏàÌá²¢ÂÛ¡££¨µÚ42-44Ò³£©</p>
+<p>ÔÚÄÏ·½Ì¸»°ÀµËСƽÓÃÖйú¾Ñé˵Ã÷ÁËͬÑùµÄ¹Ûµã¡£Ëû˵£º“Èç¹ûûÓиĸ↑·ÅµÄ³É¹û£¬‘Áù·ËÄ’Õâ¸ö¹ØÎÒÃÇ´³²»¹ý£¬´³²»¹ý¾ÍÂÒ£¬ÂҾʹòÄÚÕ½£¬‘ÎÄ»¯´ó¸ïÃü’¾ÍÊÇÄÚÕ½¡£ÎªÊ²Ã´‘Áù·ËÄ’ÒÔºóÎÒÃǵĹú¼ÒÄܹ»ºÜÎȶ¨£¿¾ÍÊÇÒòΪÎÒÃǸãÁ˸ĸ↑·Å£¬´Ù½øÁ˾¼Ã·¢Õ¹£¬ÈËÃñÉú»îµÃµ½Á˸ÄÉÆ¡£ËùÒÔ£¬¾ü¶Ó¡¢¹ú¼ÒÕþȨ£¬¶¼ÒªÎ¬»¤ÕâÌõµÀ·¡¢Õâ¸öÖÆ¶È¡¢ÕâЩÕþ²ß¡£”</p>
+
+<p>Î¥·´µÚÒ»¶¨ÂÉ£¬ÕþȨ¾Í²»Îȶ¨£¬ÄÑÃâÍöµ³Íö¹ú£¬Õâ±ãÊÇÖйú¸Ä¸ï¿ª·ÅµÄµÚ¶þ¶¨ÂÉ¡£</p>
+<p>µÚ¶þ¶¨ÂÉÊÇÖ´ÕþÕßÐËÍö¶¨ÂÉ¡£¶Ô¿¹»òÆ«ÀëµÚÒ»¶¨ÂÉ£¬¼´Ê¹ÓÐëÔó¶«ÄÇÑùµÄ´ó²Å£¬¼´Ê¹ÊÇËÕÁªÄÇÑùµÄ³¬¼¶´ó¹ú£¬×îÖÕÒ²ÄÑÌÓË¥ÍöµÄÃüÔË¡£</p>
+<p>µÚ¶þ¶¨ÂɶÏÑÔÄæÕßÍö£¬È´²»¶ÏÑÔ˳Õß²ý¡£ÓõËСƽµÄ»°Ëµ£º“²»¸Ä¸ï¿ª·Å£¬²»·¢Õ¹¾¼Ã£¬²»¸ÄÉÆÈËÃñÉú»î£¬Ö»ÄÜÊÇËÀ·һÌõ¡£”·´¹ýÀ´£¬Ë³Ó¦×ÔÓɶ¨ÂÉ£¬ÓÐÖúÓÚÖ´ÕþÕߵõ½ÃñÖÚµÄÓµ´÷¡£µ«ÃñÖÚÓµ´÷Ò»¸öÕþµ³µÄÔÒòºÜ¶à£¬¸ãºÃ¾¼ÃÖ»ÊDZØÒªÌõ¼þÖ®Ò»¡£</p>
+<p>µÚ¶þ¶¨ÂɵĿ϶¨ÐÔ±í´ïÊÇ£º×ñÑ×ÔÓɶ¨ÂÉÓëÖ´ÕþÕßµÄÐËÍú·¢´ïÕýÏà¹Ø¡£¼ÙÈçÆäËûÌõ¼þÏàͬ£¬×ñѵÚÒ»¶¨ÂÉ£¬¶ÔÖ´Õþ¼¯ÍűØÓÐÕýÃæ×÷Óá£</p>
+<p>¹ØÓÚÕâÌõ¶¨ÂÉ£¬ÃÏ×ÓÔçÓиü¼ÓÒ»°ã»¯µÄ±íÊö£º“µÃµÀÕß¶àÖú£¬Ê§µÀÕß¹ÑÖú¡£¹ÑÖúÖ®ÖÁ£¬ÇׯÝÅÏÖ®¡£¶àÖúÖ®ÖÁ£¬ÌìÏÂ˳֮¡£”¹ÅÈ˵ÄÁíÒ»ÖÖ˵·¨ÊÇ£º“µÃÈËÐÄÕßµÃÌìÏ£¬Ê§ÈËÐÄÕßʧÌìÏ¡£”</p>
+<p>Àúʷʵ¼ùÒ»ÔÙ±íÃ÷£¬×ÔÈ»¾¼Ã»ò¼Æ»®¾¼Ã²»ÈçÊг¡¾¼Ã£¬¹ØÓÚ“µÀ”µÄ¹²Ê¶ÐγÉÁË£¬ÈËÐÄËùÏò¾ÍÈ·¶¨ÁË¡£ÈËÐĵÄÖ÷Á÷ÊÇ×·ÇóÀûÒæ£¬×ñѵÚÒ»¶¨ÂÉ£¬¿ÉÒÔ´´Ôì¸ü¶àµÄ²Æ¸»£¬Òò´ËÒ²¿ÉÒÔ¸ü¶àµØÓ®µÃÈËÐÄ¡£Í¬Ê±£¬²Æ¸»Ôö¼Ó£¬Ë°»ùÀ©´ó£¬Õþ¸®Ò²Óиü¶àµÄ˰ÊÕ¡£ÓÚÊÇ£¬×ñѵÚÒ»¶¨ÂÉ£¬ÕþȨÈ˲ÆÁ½µÃ¡£·´Ö®Ôò·´ÊÇ¡£</p>
+
+<p><b>2.Æ«Àë¶È</b></p>
+<p>ÆÕ¾©Ëµ£¬ËÕÁªÆ«ÀëÈËÀàµÄ¿µ×¯´óµÀ½«½ü70Äê¡£ÏÔÈ»£¬Æ«ÀëµÚÒ»¶¨ÂÉ£¬²»ÖÁÓÚÁ¢¿Ìµ¼ÖÂÕþȨ¿ą̊¡£</p>
+<p>ÔÚÃñÖ÷ÖÆ¶ÈÏ£¬Ñ¡Ãñ¿ÉÄÜ×óÓÒÒ¡°Ú£¬ÔÚij¸öʱÆÚͶƱÔÞ³ÉijÖÖ³Ì¶ÈµÄÆ«Àë¡£¼´Ê¹²»Ô޳ɣ¬Ö»Òª²»Ì«¹ý·Ö£¬Ò²ÒªµÈµ½ÏÂÒ»´ÎÑ¡¾Ù¾ÀÆ«¡£ÓÚÊÇ£¬Ò»½ìÈÎÆÚµÄÆ«À룬¾Í¿ÉÒÔ¿´×÷³£¹æµÄÆ«Àëʱ¼ä¡£Èç¹ûÁìµ¼ÈËʵÐÐÖÕÉíÖÆ£¬Æ«Àë¾Í¿ÉÄܳÖÐøÊýÊ®Äê¡£Èç¹ûʵÐÐÊÀÏ®ÖÆ£¬Æ«Àëʱ¼äÉõÖÁ¿ÉÄܳÖÐøÊý´ú¡£</p>
+<p>´Ó¿Õ¼ä·½Ãæ¿´£¬Æ«Àë½Ç¶ÈÒ²Óкܴó²î±ð¡£30¶ÈÊÇÆ«£¬90¶ÈÒ²ÊÇÆ«£¬»¹ÓпÉÄܳöÏÖ180¶ÈµÄµ¹ÐÐÄæÊ©¡£Öйú¹²²úµ³Ö´Õþ£¬´Ó»¥Öú×鿪ʼ×óÆ«£¬¾ºÏ×÷Éçµ½ÈËÃñ¹«ÉçÖ±ÖÁ´óÔ¾½ø£¬Æ«Àë¶ÈÔ½À´Ô½¸ß£¬ÔÖÄÑÒ²Ô½À´Ô½´ó£¬Ô½À´Ô½ÄÑÒÔ³ÖÐø¡£</p>
+<p>Æ«ÀëµÄÖ÷ÒªÔÒò£¬ÊÇÖ´ÕþÕßÓµÓÐ×ÔÉíÀûÒæ»ò¶ÀÌØÐÅÑö¡£ÀÏ×ÓËùνµÄ“Ê¥ÈËÎÞÐÄ£¬ÒÔ°ÙÐÕÖ®ÐÄΪÐÄ”£¬ÊµÐÐÆðÀ´£¬»òÕßÐèҪʥÈËÒ»°ãµÄÈ˸ñÁ¦Á¿£¬»òÕßÐèÒª°ÙÐÕ˵ÁËËãµÄÃñÖ÷ÖÆ¶È¡£</p>
+<p>×ÜÖ®£¬Æ«ÀëÒòÖ´ÕþÕßµÄÀûÒæ¶øÉú£¬Æ«Àë¶ÈÊÇÆ«Àë¿Õ¼äÓëʱ¼äµÄ³Ë»ý£¬Æ«Àë¶ÈÊܵ½ÊÚÈ¨ÖÆ¶ÈÏÞÖÆ£¬Æ«Àë¶ÈÓëÕþȨµÄ²»Îȶ¨³Ì¶È³ÉÕý±È¡£</p>
+<p>ÔÚ¸ü¿í¹ãµÄÊÓÒ°ÀƫÀë¶È»¹Êܵ½Ò»Ð©¸ü»ù±¾ÒòËØµÄÏÞÖÆ¡£ÀýÈçÀúÊ·ÉÏÐÂÖÆ¶ÈµÄ³öÏÖ¡¢¶ÔÕýµÀµÄÐÂÈÏʶ¡¢¾ÀÆ«µÄÄÚ²¿³É±¾ºÍÍⲿÁ¦Á¿µÈµÈ¡£</p>
+<p>1992Ä꣬µËСƽÔÚÄÏ·½Ì¸»°ÖÐ˵£º“ÏÖÔÚ£¬ÖܱßһЩ¹ú¼ÒºÍµØÇø¾¼Ã·¢Õ¹±ÈÎÒÃǿ죬Èç¹ûÎÒÃDz»·¢Õ¹»ò·¢Õ¹µÃÌ«Âý£¬ÀϰÙÐÕÒ»±È½Ï¾ÍÓÐÎÊÌâÁË¡£”˳×ÅÕâÖÖ˼·׷ÎÊÏÂÈ¥£¬¿ÉÒÔ·¢ÏÖ¾ÀÆ«Õß¿¼ÂǵĻù±¾ÒòËØ¡£</p>
+
+<p>Ê×ÏÈ£¬ÎªÊ²Ã´»áÓÐÎÊÌ⣿ÎÊÌâÀ´×ÔÆ«Àë¡£Öܱ߹ú¼ÒµÄ¾¼Ã×ÔÓɶȸߣ¬¾¼Ã·¢Õ¹¿ì£¬°´ÕÕ·¢Õ¹ÊÇÓ²µÀÀíµÄ˵·¨£¬·¢Õ¹¿ìµÄµÀ·¾ÍÊÇÕýµÀ¡£Èç¹ûÈ«ÈËÀàÈÔÔÚÃþË÷Ö®ÖУ¬Ìì϶¼ÊÇ×Ô¸ûÅ©»ò·â½¨×¯Ô°£¬×ÔÈ»¾¼Ã¾ÍÊÇÕýµÀ£¬µ±È»²»´æÔÚÆ«ÀëÎÊÌ⣬»ù±¾¾¼Ãģʽ¿ÉÒÔǧÄê²»±ä¡£Èç¹ûÍⲿÓÐÁËЧÂʸü¸ßµÄÖÆ¶È£¬Æ«ÀëÕýµÀµÄÎÊÌâ³öÏÖ£¬µ«Ã»ÓбȽϣ¬±Õ¹ØËø¹ú£¬ÊµÐÐÓÞÃñÕþ²ß£¬·âɱ»òŤÇú¶Ô×ÔÉí²»ÀûµÄÍⲿÐÅÏ¢£¬ÄÚ²¿ÎÊÌâÒ²²»´ó¡£</p>
+<p>Æä´Î£¬ÓÐʲôÎÊÌ⣿ÍⲿÎÊÌâÊÇ£¬·â±ÕµÄ´óÃÅ¿ÉÄܱ»×²¿ª£¬ÐÅÏ¢·âËø¿ÉÄÜÓЩ¶´£¬Î¬³Ö·â±ÕµÄ³É±¾¿ÉÄܸߵ½µÃ²»³¥Ê§µÄµØ²½¡£×îºó£¬Æ«ÀëÕß»¹¿ÉÄÜÔÚ¹ú¼Ê¾ºÕùÖб»Ç¿ÕßÌÔÌ¡£</p>
+<p>ÄÚ²¿ÎÊÌâÊÇ£º¶Ô±È֮ϲúÉúµÄ²»Âú¡£ÃñÖÚ×·Çó¸ü¶àµÄÀûÒæ£¬¶ÔÆ«ÀëÕýµÀ²»Âú¡£Ö´Õþ¼¯ÍÅÀïÒ²»áÓÐÈË×·ÇóÃñÖÚµÄÓµ´÷£¬×·Çó¸ü¶àµÄ˰ÊÕ£¬Í¬Ñù¶ÔÆ«ÀëÕýµÀ²»Âú¡£Æ«Àë¶ÈÔ½¸ß£¬²»ÂúÔ½ÑÏÖØ¡£ÑÏÖØÖ®ÖÁ£¬“ÇׯÝÅÏÖ®”¡£Èç¹û¾ÀÆ«µÄÊÕÒæ¿ÉÒԻݼ°È«Éç»á£¬ÄÇô£¬¾ÀÆ«½«³ÉΪÉç»á¸÷½×²ãµÄÆÕ±éÒªÇó£¬Ö´Õþ¼¯ÍÅÄÚ²¿Ò²ÓзÖÁѵÄΣÏÕ¡£Èç¹û¸Ä¸ïÊÕÒæÖ÷Òª»Ý¼°ÃñÖÚ£¬¶ÔÖ´Õþ¼¯ÍŲ»Àû£¬ÕâÖÖÆ«ÀëÈÔ¿ÉÄܳÖÐø£¬¸Ä¸ï¾Í¿ÉÄÜÍÏÑÓ£¬µ«¹ÙÃñì¶Ü½«Öð²½¼¤»¯£¬Ö±ÖÁ×îºó±¬·¢¡£</p>
+<p>·´¹ýÀ´Ëµ£¬Æ«ÀëÓÐΣÏÕ£¬¾ÀƫҲÊÇÓгɱ¾µÄ¡£¾ÀÆ«Á¦Á¿µÄ¾Û¼¯ºÍ·¢¶¯£¬ÄÑÃ⸶³öÉúÃüµÄ´ú¼Û£¬ÉõÖÁ·¢Õ¹µ½ÑªÁ÷³ÉºÓµÄµØ²½¡£ÓÉÇØººµ½Ãñ¹úµÄ¾Ñé½Ìѵ¿ÉÒÔ¿´³ö£¬ÎÞÂÛ¾ÀÆ«µÄÁ¦Á¿À´×ÔÄÚ²¿»¹ÊÇÍⲿ£¬ÔÚÆä³É±¾µÄ±ê¸ß֮ϣ¬¶¼ÊÇÆ«ÀëµÄ´æÔڿռ䡣ÔÚ´Ë·¶Î§ÄÚ£¬¾ö²ßÕß²»½öÓµÓо޴óµÄÑ¡ÔñÓàµØ£¬»¹Äܽ¨Á¢×Ô¼ºµÄ¼ÛÖµ¹Û£¬²¢ÓÃÕâÌ×¼ÛÖµ¹Û½Ì»¯ÃñÖÚ£¬À©Õ¹Æ«Àë¿Õ¼ä¡£</p>
+<p><b>3.Æ«Àë¶ÈµÄ±ØÔö±Ø¼õ</b></p>
+<p>ÔÚ¡¶Îª½¨ÉèÒ»¸ö¸»Ç¿ÃñÖ÷ÎÄÃ÷µÄÉç»áÖ÷Òå¹ú¼Ò¶ø·Ü¶·¡·Ò»ÎÄÖУ¬Ìï¼ÍÔÆ»Ø¹ËµÀ£º“¹ýÈ¥·¢ÉúµÄÄÇЩ´íÎ󣬰üÀ¨Ê®Äê‘ÎÄ»¯´ó¸ïÃü’µÄÀúÊ·±¯¾ç£¬ÔÒòÊǸ´Ôӵģ¬ÎÒ¿´×îÖØÒªµÄÔÒòÖ®Ò»¾ÍÊÇȱ·¦ÃñÖ÷Óë·¨ÖÆ£¬ÈËÖλ¹ÊÇ·¨ÖÎÎÊÌâÔÚÈÏʶÉϺÍʵ¼ùÉÏûÓеõ½¸ù±¾½â¾ö¡£Èç¹ûÊÇÕæÕýµÄ·¨Öιú¼Ò£¬¾Í³öÏÖ²»ÁËÕâÖÖÇé¿ö£¬¼´Ê¹³öÏÖÁË£¬Ò²²»¿ÉÄÜ·¢Õ¹µ½ÄÇôÑÏÖØµÄ³Ì¶È¡£”£¨µÚ450Ò³£©</p>
+
+<p>ʲô½ÐÈËÖΣ¿Ìï¼ÍÔÆµÄ½âÊÍÊÇ£º“»ÊµÛÊÇÌìϵÄÖÁ×ð£¬Ëû¿ÉÒÔÒÔÑÔ´ú·¨£¬ÒÔÑÔ·Ï·¨¡£Ëùν‘Ò»ÑÔÐ˰¬‘Ò»ÑÔÉ¥°î’£¬‘ÈËÔÚÕþÔÚ’£¬‘ÈËÍöÕþÏ¢’£¬¾ÍÊÇÈËÖεıíÏÖ¡£”»»¾ä»°Ëµ£¬ÈËÖÎÉç»á¾ÍÊǸöÈË׍֯Éç»á¡£</p>
+<p>¹ØÓÚÈËÖÎÉç»á£¬Ìï¼ÍÔÆÒ²Ìá³öÁËÁ½Ìõ¹æÂÉÐԵĿ´·¨¡£</p>
+<p>µÚÒ»£¬“Èç¹ûûÓз¨ÂɵÄÔ¼Êø£¬Ã»ÓÐÇ¿ÓÐÁ¦µÄ¼à¶½£¬ÕÆÎÕȨÁ¦µÄÈ˾ÍÍùÍù»áÀÄÓÃ×Ô¼ºÊÖÖеÄȨÁ¦£¬ÕâÊǹŽñÖÐÍâÀúÊ·Ò»ÔÙÖ¤Ã÷Á˵ÄÒ»Ìõ¶¨ÂÉ¡£”</p>
+
+<p>µÚ¶þ£¬“±÷ÆúÈËÖΣ¬ÊµÐÐÉç»áÖ÷Òå·¨ÖΣ¬ÕâÊÇÈËÃñµÄÒªÇó£¬ÊÇÀúÊ·µÄ·¢Õ¹¹æÂÉ£¬Ò²ÊÇÎÒÃǹú¼Ò×ßÏò·±ÈÙ²ýÊ¢¡¢ÒÔÇ¿´óµÄ×Ë̬ÒÙÁ¢ÓÚÊÀ½çÃñ×åÖ®ÁֵıØÓÉ֮·¡£”</p>
+<p>ÎªÊ²Ã´ÕÆÎÕȨÁ¦µÄÍùÍù»áÀÄÓÃ×Ô¼ºÊÖÖеÄȨÁ¦£¿ÒòΪ£¬ÈκÎÈ˶¼ÓÐÀûÓÃ×Ô¼ºÕÆÎÕµÄ×ÊÔ´»ñÈ¡×î¸ßÊÕÒæµÄÇãÏò£¬Í¶×ÊÈç´Ë£¬ÀͶ¯Èç´Ë£¬Ê¹ÓÃȨÁ¦Ò²Èç´Ë¡£Ö»ÒªÊÕÒæ´óÓڳɱ¾£¬²»ÊÜÖÆÔ¼£¬È¨Á¦À©ÕűãÎÞÖ¹¾³£¬ÎÞÂÛ´óȨСȨ£¬¸ß²ã»ù²ã¡£´óÊÆËùÇ÷£¬Æ«ÀëÕýµÀÊDZØÈ»µÄ£¬¶øÇÒÊǵÝÔöµÄ£¬ÓúÑÝÓúÁҵġ£</p>
+<p>Ϊʲô×ßÏòÃñÖ÷·¨ÖÎÊÇÀúÊ·µÄ·¢Õ¹¹æÂÉ£¿ÒòΪ£¬È±·¦ÃñÖ÷·¨ÖΣ¬×ÔÓɵò»µ½±£ÕÏ£¬È¨Á¦ËæÊ±¿ÉÄÜÆ«ÀëÕýµÀ£¬Ôì³ÉÒ¡°Ú¶¯µ´£¬×îÖÕÂäºóÓÚʱ´ú¡£Õâʱºò£¬µÚ¶þ¶¨ÂÉÏÔʾ×÷Óã¬Ö´ÕþÕßË¥Íö¡£×îºó£¬»îÏÂÀ´µÄ£¬³¤ÆÚ·±Èٵ쬶¼ÊÇÕþ¸®·þ´ÓÑ¡Ãñ£¬±£»¤¹«Ãñ×ÔÓÉ£¬Æ«Àë¶È±È½ÏµÍµÄ¹ú¼Ò¡£</p>
+</div><!--end #text-->
+ <div id="pageNum"><div class="pages"><span class="nextprev">ÉÏÒ»Ò³</span><span title="µ±Ç°Ò³Ãæ" class="current">1</span><a href="http://www.infzm.com/content/35685/1" title="Ìøµ¹µÚ2Ò³" >2</a><a href="http://www.infzm.com/content/35685/1" title="Ìøµ¹µÚ2Ò³" >ÏÂÒ»Ò³</a></div></div><!--end #pageNum-->
+ <div class="clear"></div>
+ <!--ÔðÈαà¼+ÍøÂç±à¼-->
+
+ <div id="editor">
+ ÔðÈαà¼: ÁõСÀÚ
+
+ </div><!--end #editor-->
+ </div><!--end .contents-->
+ </div><!--end #detailContent-->
+ </div><!--end .grid_8-->
+ <div class="grid_4">
+ <div class="mm"></div>
+
+ <!--ÐÂÎŵØÍ¼-->
+ <div id="newsMap" class="mods_contentbycatid_newsmap frame gray_e">
+ <div class="header">
+ <h3>ÐÂÎŵØÍ¼</h3>
+ </div>
+ <div class="body">
+ <a href="http://www.infzm.com/newsmap/index.php" target="_blank"><img src="/2008/images/map.png" width="260"/></a>
+ <ul class="newslist">
+
+ <li>
+ <p><a href="http://www.infzm.com/newsmap/index.php?id=35749" TARGET="_blank" >Ò©¼àÆØ¹â5ÖÖÍøÉϼÙÒ©</a></p>
+ </li>
+ <li>
+ <p><a href="http://www.infzm.com/newsmap/index.php?id=35751" TARGET="_blank" >¾¯Ìè¼ÓÌæÉ³ÐDz»Á¼·´Ó¦</a></p>
+ </li>
+ <li>
+ <p><a href="http://www.infzm.com/newsmap/index.php?id=35745" TARGET="_blank" >ÉϺ£³ö×â³µµ÷¼Û</a></p>
+
+ </li>
+ <li>
+ <p><a href="http://www.infzm.com/newsmap/index.php?id=35748" TARGET="_blank" >ÖÐʯÓͽ«¿ª·¢ÒÁÀ¿ËÓÍÌï</a></p>
+ </li>
+ <li>
+ <p><a href="http://www.infzm.com/newsmap/index.php?id=35747" TARGET="_blank" >·ÆÂɱö±©ÓêÖÂɽÌ廬ÆÂ</a></p>
+ </li>
+ <li>
+
+ <p><a href="http://www.infzm.com/newsmap/index.php?id=35750" TARGET="_blank" >ÁªºÏ¹ú·É»ú×¹»Ù</a></p>
+ </li>
+ <li>
+ <p><a href="http://www.infzm.com/newsmap/index.php?id=35746" TARGET="_blank" >ÃÀÁª´¢·Å·çÊÕ½ô»õ±ÒÕþ²ß</a></p>
+ </li>
+ <li>
+ <p><a href="http://www.infzm.com/newsmap/index.php?id=35737" TARGET="_blank" >µÚ¶þ´ÎÖÐÈÕº«·å»á</a></p>
+
+ </li>
+ </ul>
+ </div>
+ <div class="footer"></div>
+</div> <div class="space h20"></div>
+ <div class="mm"></div>
+ <!--Top10-->
+ <script type="text/javascript">
+var top10_tab_nomber;
+function showTops( t_no )
+{
+ $ES("#tabs li").each(function(e){
+ if("tab_"+t_no == e.id){
+ !e.hasClass( "action" ) && e.addClass( "action" );
+ top10_tab_nomber = t_no;
+ } else {
+ e.removeClass( "action" );
+ }
+ });
+ for ( var i=0; i < 2 ; i++) {
+ $('t_'+i).setStyle( "display","none" );
+ }
+ $('t_'+t_no).setStyle( "display","" );
+
+ showtopbytime(0);
+}
+window.addEvent("domready",function(){
+ showTops(0);
+});
+</script>
+
+<div id="Top10" class="mods_top10_homedefault frame">
+ <div class="header">
+ <h3>Ê®´óÈÈÃÅ</h3>
+ <div class="model-tab-nav">
+ <ul id="tabs">
+ <li id="tab_0" onclick="showTops(0);"><a href="javascript:void(0);"><span>ÎÄÕÂ</span></a></li>
+ <li id="tab_1" class="action" onclick="showTops(1);"><a href="javascript:void(0);"><span>ÍøÕª</span></a></li>
+ </ul>
+
+ </div>
+ </div>
+ <div id="t_0" class="body">
+ <ul id="ul_0_0" class="newslist hot" style="display:block">
+ <li><a href="http://www.infzm.com/content/35735" TARGET="_blank"><em><i>0</i>1.<i>0</i></em>Îä´ó¹ÙÍø·¢²¼ÏûÏ¢³Æ¸±Ð£³¤Ó븱Êé¼ÇÉæÏÓ...</a></li>
+ <li><a href="http://www.infzm.com/content/35741" TARGET="_blank"><em><i>0</i>2.<i>0</i></em>ÓàÇïÓêÐÂÊéÃæÊÀ£¬·ÅÑÔ¡°Ò§Óàרҵ»§¡±¶¼...</a></li>
+
+ <li><a href="http://www.infzm.com/content/35588" TARGET="_blank"><em><i>0</i>3.<i>0</i></em>ÄãµÃÀûÈó£¬ÎÒÀ´Âñµ¥</a></li>
+ <li><a href="http://www.infzm.com/content/35457" TARGET="_blank"><em><i>0</i>4.<i>0</i></em>½ÌÓý²¿£ºÖйú¸ßУ¿ÆÑÐÄÜÁ¦ÊÀ½çµÚÎå</a></li>
+ <li><a href="http://www.infzm.com/content/35560" TARGET="_blank"><em><i>0</i>5.<i>0</i></em>¹û¸ÒÓàÉú ÖйúÊÇËûÃÇΩһµÄÏ£Íû</a></li>
+
+ <li><a href="http://www.infzm.com/content/35583" TARGET="_blank"><em><i>0</i>6.<i>0</i></em>¡¾Ð´Õæ¡¿Ôıø¡¤¼â¶ËÀûÆ÷¶á¿áÉ</a></li>
+ <li><a href="http://www.infzm.com/content/35566" TARGET="_blank"><em><i>0</i>7.<i>0</i></em>ÁìÐäÍòËê¹ú¼ÒÍòË껹ÓÐÈËÃñÍòËê</a></li>
+ <li><a href="http://www.infzm.com/content/35744" TARGET="_blank"><em><i>0</i>8.<i>0</i></em>°Â°ÍÂíÈÙ»ñŵ±´¶ûºÍƽ½±</a></li>
+
+ <li><a href="http://www.infzm.com/content/35589" TARGET="_blank"><em><i>0</i>9.<i>0</i></em>Ìáʾ¡°ÎÂܰ¡±ÔÚÄÄÀï</a></li>
+ <li><a href="http://www.infzm.com/content/35634" TARGET="_blank"><em>10.<i>0</i></em>¸£½¨ÉϺ¼ÏØ£ºÇ¦Öж¾¿Ö»ÅÖ®ºó</a></li>
+ </ul>
+ <ul id="ul_0_1" class="newslist hot" style="display:none">
+ <li><a href="http://www.infzm.com/content/35439" TARGET="_blank"><em><i>0</i>1.<i>0</i></em>¡°²»·¢Õ¹¡±µÄȨÁ¦</a></li>
+
+ <li><a href="http://www.infzm.com/content/35735" TARGET="_blank"><em><i>0</i>2.<i>0</i></em>Îä´ó¹ÙÍø·¢²¼ÏûÏ¢³Æ¸±Ð£³¤Ó븱Êé¼ÇÉæÏÓ...</a></li>
+ <li><a href="http://www.infzm.com/content/35457" TARGET="_blank"><em><i>0</i>3.<i>0</i></em>½ÌÓý²¿£ºÖйú¸ßУ¿ÆÑÐÄÜÁ¦ÊÀ½çµÚÎå</a></li>
+ <li><a href="http://www.infzm.com/content/35583" TARGET="_blank"><em><i>0</i>4.<i>0</i></em>¡¾Ð´Õæ¡¿Ôıø¡¤¼â¶ËÀûÆ÷¶á¿áÉ</a></li>
+
+ <li><a href="http://www.infzm.com/content/35560" TARGET="_blank"><em><i>0</i>5.<i>0</i></em>¹û¸ÒÓàÉú ÖйúÊÇËûÃÇΩһµÄÏ£Íû</a></li>
+ <li><a href="http://www.infzm.com/content/35470" TARGET="_blank"><em><i>0</i>6.<i>0</i></em>ÐÂÖйúÁùÊ®ÖÜÄêÌØ¿¯¡¤×ÊÖÎͨ¼ø</a></li>
+ <li><a href="http://www.infzm.com/content/35741" TARGET="_blank"><em><i>0</i>7.<i>0</i></em>ÓàÇïÓêÐÂÊéÃæÊÀ£¬·ÅÑÔ¡°Ò§Óàרҵ»§¡±¶¼...</a></li>
+
+ <li><a href="http://www.infzm.com/content/35588" TARGET="_blank"><em><i>0</i>8.<i>0</i></em>ÄãµÃÀûÈó£¬ÎÒÀ´Âñµ¥</a></li>
+ <li><a href="http://www.infzm.com/content/35566" TARGET="_blank"><em><i>0</i>9.<i>0</i></em>ÁìÐäÍòËê¹ú¼ÒÍòË껹ÓÐÈËÃñÍòËê</a></li>
+ <li><a href="http://www.infzm.com/content/35441" TARGET="_blank"><em>10.<i>0</i></em>ÈËÒªÕ¾Æð¿¿×Ô¼º</a></li>
+
+ </ul>
+ <ul id="ul_0_2" class="newslist hot" style="display:none">
+ <li><a href="http://www.infzm.com/content/34874" TARGET="_blank"><em><i>0</i>1.<i>0</i></em>½»¹ÜÈËÔ±×°²¡ÇóÖú ³µÖ÷ºÃÐÄ´î¿Í±»³ÆºÚ...</a></li>
+ <li><a href="http://www.infzm.com/content/34464" TARGET="_blank"><em><i>0</i>2.<i>0</i></em>¶Ôμұ¦µÄ¸öÈËÒâ¼û</a></li>
+ <li><a href="http://www.infzm.com/content/34763" TARGET="_blank"><em><i>0</i>3.<i>0</i></em>ÉâÃâ̰¹Ù"Ô×ï"»»È¡²Æ²ú¹«Ê¾À×È˹¹Ïë...</a></li>
+
+ <li><a href="http://www.infzm.com/content/34674" TARGET="_blank"><em><i>0</i>4.<i>0</i></em>¡¶ÖìéF»ù´ð¼ÇÕßÎÊ¡·³ö°æÊ¼Ä©</a></li>
+ <li><a href="http://www.infzm.com/content/25786" TARGET="_blank"><em><i>0</i>5.<i>0</i></em>ΪʲôÃñÖÚ²»ÒÔ͵˰Ϊ³Ü£¿</a></li>
+ <li><a href="http://www.infzm.com/content/35311" TARGET="_blank"><em><i>0</i>6.<i>0</i></em>ÄãËù²»ÖªµÀµÄÒ»¾ÅËľšª¡ª¶Ô»°ÁúӦ̨</a></li>
+
+ <li><a href="http://www.infzm.com/content/35173" TARGET="_blank"><em><i>0</i>7.<i>0</i></em>¡°µöÓãÖ´·¨¡±ºÏ·¨ÐÔÔâÖÊÒÉ ´¥¼°µÀµÂµ×...</a></li>
+ <li><a href="http://www.infzm.com/content/35266" TARGET="_blank"><em><i>0</i>8.<i>0</i></em>±¡ÎõÀ´ÖÎÓå¹Û²ì</a></li>
+ <li><a href="http://www.infzm.com/content/35177" TARGET="_blank"><em><i>0</i>9.<i>0</i></em>¡°ÎÃ×ӷɹý£¬Ò²Òª´òÏÂÀ´¡±</a></li>
+
+ <li><a href="http://www.infzm.com/content/35470" TARGET="_blank"><em>10.<i>0</i></em>ÐÂÖйúÁùÊ®ÖÜÄêÌØ¿¯¡¤×ÊÖÎͨ¼ø</a></li>
+ </ul>
+ <ul id="ul_0_3" class="newslist hot" style="display:none">
+ <li><a href="http://www.infzm.com/content/23337" TARGET="_blank"><em><i>0</i>1.<i>0</i></em>¸ßÈýѧÉú£ºÎÒ±»Öйú½ÌÓý±Æ·èÁË</a></li>
+ <li><a href="http://www.infzm.com/content/22024" TARGET="_blank"><em><i>0</i>2.<i>0</i></em>¡¾2009ÄêÐÂÄêÏ×´Ê¡¿Ã»ÓÐÒ»¸ö¶¬Ìì²»...</a></li>
+
+ <li><a href="http://www.infzm.com/content/27790" TARGET="_blank"><em><i>0</i>3.<i>0</i></em>ËɱËÀÁËÀîÀöÔÆ£¿¡°ÕÉ·ò¾ÜÇ©ÊÖÊõÖÂÔи¾...</a></li>
+ <li><a href="http://www.infzm.com/content/24467" TARGET="_blank"><em><i>0</i>4.<i>0</i></em>³¹µ×Õû¶Ù¸ßµÈ½ÌÓýÊ®Òâ¼ûÊé</a></li>
+ <li><a href="http://www.infzm.com/content/26713" TARGET="_blank"><em><i>0</i>5.<i>0</i></em>¡°ÖÂÃü¡±µÄÍí×Ôϰ</a></li>
+
+ <li><a href="http://www.infzm.com/content/21056" TARGET="_blank"><em><i>0</i>6.<i>0</i></em>ÄÏ·½ÖÜÄ©1998Äê¶ÈÈËÎÖìéF»ù</a></li>
+ <li><a href="http://www.infzm.com/content/25786" TARGET="_blank"><em><i>0</i>7.<i>0</i></em>ΪʲôÃñÖÚ²»ÒÔ͵˰Ϊ³Ü£¿</a></li>
+ <li><a href="http://www.infzm.com/content/17700" TARGET="_blank"><em><i>0</i>8.<i>0</i></em>¡¾Ð´Õæ¡¿Ò»´Îº½ÅĵÄÒâÍâ·¢ÏÖ£ºÉ˺Û</a></li>
+
+ <li><a href="http://www.infzm.com/content/26550" TARGET="_blank"><em><i>0</i>9.<i>0</i></em>Ò»¸öÌåÓýÉúµÄâ§ËÀ</a></li>
+ <li><a href="http://www.infzm.com/content/20899" TARGET="_blank"><em>10.<i>0</i></em>372ÄêÊØÄ¹Ê·ÇúÖÕÈËÉ¢</a></li>
+ </ul>
+ <p class="more"><a href="">¸ü¶à...</a></p>
+ </div>
+
+
+ <div id="t_1" class="body" style="display:none;">
+ <ul id="ul_1_0" class="newslist hot" style="display:block">
+ <li><a href="http://p.infzm.com/link/85667" TARGET="_blank"><em><i>0</i>1.<i>0</i></em>µçÊÓ¹ºÎïµÄ±©ÀûÄÚÄ»</a></li>
+ <li><a href="http://p.infzm.com/link/85659" TARGET="_blank"><em><i>0</i>2.<i>0</i></em>Ó¡ÄáÎ÷צÍÛÊ¡·¢ÉúÀïÊÏ7.3¼¶µØÕð,ÓÐ...</a></li>
+ <li><a href="http://p.infzm.com/link/85533" TARGET="_blank"><em><i>0</i>3.<i>0</i></em>Öйúµç×Ó»ú½öÈýÃë¼´Ëø¶¨ÃÀÔ¤¾¯»ú_²©¿Í...</a></li>
+
+ <li><a href="http://p.infzm.com/link/85669" TARGET="_blank"><em><i>0</i>4.<i>0</i></em>¾Æ¾®·¨×ÓÀë»éÔâ¾Ü ËðʧÈýǧÍò</a></li>
+ <li><a href="http://p.infzm.com/link/85666" TARGET="_blank"><em><i>0</i>5.<i>0</i></em>ÃÏÍ¥ÎÁ¦Í¦ËÄÇ¿¿ìÅ®Óô¿ÉΨ_Öйú½á»éÍø...</a></li>
+ <li><a href="http://p.infzm.com/link/85665" TARGET="_blank"><em><i>0</i>6.<i>0</i></em>ÁõµÂ»ª·µ¸Û±»¶Â½Ø ³ÐÈÏÓëÓ÷¿ÉÐÀÇ©»éÊé...</a></li>
+
+ <li><a href="http://p.infzm.com/link/85640" TARGET="_blank"><em><i>0</i>7.<i>0</i></em>Öí¸ÎÖνüÊÓÂð</a></li>
+ <li><a href="http://p.infzm.com/link/85632" TARGET="_blank"><em><i>0</i>8.<i>0</i></em>2009¿ªÑ§µÚÒ»¿Î¡¶ÎÒ°®ÄãÖйú¡·¡¾Íê...</a></li>
+ <li><a href="http://p.infzm.com/link/85624" TARGET="_blank"><em><i>0</i>9.<i>0</i></em>ÖйúÍ⽻ʷÉϵÄÅ£ÈËÅ£Óï</a></li>
+
+ <li><a href="http://p.infzm.com/link/85532" TARGET="_blank"><em>10.<i>0</i></em>´ó±äÃÀÅ®£¬´Ó³óµ½ÃÀ¾ÍÊÇÕâô¼òµ¥£¨×éͼ...</a></li>
+ </ul>
+ <ul id="ul_1_1" class="newslist hot" style="display:none">
+ <li><a href="http://p.infzm.com/link/85667" TARGET="_blank"><em><i>0</i>1.<i>0</i></em>µçÊÓ¹ºÎïµÄ±©ÀûÄÚÄ»</a></li>
+ <li><a href="http://p.infzm.com/link/85624" TARGET="_blank"><em><i>0</i>2.<i>0</i></em>ÖйúÍ⽻ʷÉϵÄÅ£ÈËÅ£Óï</a></li>
+
+ <li><a href="http://p.infzm.com/link/85659" TARGET="_blank"><em><i>0</i>3.<i>0</i></em>Ó¡ÄáÎ÷צÍÛÊ¡·¢ÉúÀïÊÏ7.3¼¶µØÕð,ÓÐ...</a></li>
+ <li><a href="http://p.infzm.com/link/85669" TARGET="_blank"><em><i>0</i>4.<i>0</i></em>¾Æ¾®·¨×ÓÀë»éÔâ¾Ü ËðʧÈýǧÍò</a></li>
+ <li><a href="http://p.infzm.com/link/85666" TARGET="_blank"><em><i>0</i>5.<i>0</i></em>ÃÏÍ¥ÎÁ¦Í¦ËÄÇ¿¿ìÅ®Óô¿ÉΨ_Öйú½á»éÍø...</a></li>
+
+ <li><a href="http://p.infzm.com/link/85665" TARGET="_blank"><em><i>0</i>6.<i>0</i></em>ÁõµÂ»ª·µ¸Û±»¶Â½Ø ³ÐÈÏÓëÓ÷¿ÉÐÀÇ©»éÊé...</a></li>
+ <li><a href="http://p.infzm.com/link/85640" TARGET="_blank"><em><i>0</i>7.<i>0</i></em>Öí¸ÎÖνüÊÓÂð</a></li>
+ <li><a href="http://p.infzm.com/link/85632" TARGET="_blank"><em><i>0</i>8.<i>0</i></em>2009¿ªÑ§µÚÒ»¿Î¡¶ÎÒ°®ÄãÖйú¡·¡¾Íê...</a></li>
+
+ <li><a href="http://p.infzm.com/link/85533" TARGET="_blank"><em><i>0</i>9.<i>0</i></em>Öйúµç×Ó»ú½öÈýÃë¼´Ëø¶¨ÃÀÔ¤¾¯»ú_²©¿Í...</a></li>
+ <li><a href="http://p.infzm.com/link/72353" TARGET="_blank"><em>10.<i>0</i></em>µ±¡°·¨ÂÉ¡±³ÉΪõåõï°ÙÐյŤ¾ßʱ¡ª¡ªÆà...</a></li>
+ </ul>
+ <ul id="ul_1_2" class="newslist hot" style="display:none">
+ <li><a href="http://p.infzm.com/link/85667" TARGET="_blank"><em><i>0</i>1.<i>0</i></em>µçÊÓ¹ºÎïµÄ±©ÀûÄÚÄ»</a></li>
+
+ <li><a href="http://p.infzm.com/link/85624" TARGET="_blank"><em><i>0</i>2.<i>0</i></em>ÖйúÍ⽻ʷÉϵÄÅ£ÈËÅ£Óï</a></li>
+ <li><a href="http://p.infzm.com/link/85669" TARGET="_blank"><em><i>0</i>3.<i>0</i></em>¾Æ¾®·¨×ÓÀë»éÔâ¾Ü ËðʧÈýǧÍò</a></li>
+ <li><a href="http://p.infzm.com/link/85666" TARGET="_blank"><em><i>0</i>4.<i>0</i></em>ÃÏÍ¥ÎÁ¦Í¦ËÄÇ¿¿ìÅ®Óô¿ÉΨ_Öйú½á»éÍø...</a></li>
+
+ <li><a href="http://p.infzm.com/link/60541" TARGET="_blank"><em><i>0</i>5.<i>0</i></em>һƬÎÀÉú½íÕü¾ÈÁËÈ«ÈËÀà</a></li>
+ <li><a href="http://p.infzm.com/link/85659" TARGET="_blank"><em><i>0</i>6.<i>0</i></em>Ó¡ÄáÎ÷צÍÛÊ¡·¢ÉúÀïÊÏ7.3¼¶µØÕð,ÓÐ...</a></li>
+ <li><a href="http://p.infzm.com/link/85533" TARGET="_blank"><em><i>0</i>7.<i>0</i></em>Öйúµç×Ó»ú½öÈýÃë¼´Ëø¶¨ÃÀÔ¤¾¯»ú_²©¿Í...</a></li>
+
+ <li><a href="http://p.infzm.com/link/58237" TARGET="_blank"><em><i>0</i>8.<i>0</i></em>ÄÏÖÜÑÔÂÛ×ÔÓɵĵ¹ÍË</a></li>
+ <li><a href="http://p.infzm.com/link/85665" TARGET="_blank"><em><i>0</i>9.<i>0</i></em>ÁõµÂ»ª·µ¸Û±»¶Â½Ø ³ÐÈÏÓëÓ÷¿ÉÐÀÇ©»éÊé...</a></li>
+ <li><a href="http://p.infzm.com/link/85640" TARGET="_blank"><em>10.<i>0</i></em>Öí¸ÎÖνüÊÓÂð</a></li>
+
+ </ul>
+ <ul id="ul_1_3" class="newslist hot" style="display:none">
+ <li><a href="http://p.infzm.com/link/58237" TARGET="_blank"><em><i>0</i>1.<i>0</i></em>ÄÏÖÜÑÔÂÛ×ÔÓɵĵ¹ÍË</a></li>
+ <li><a href="http://p.infzm.com/link/79269" TARGET="_blank"><em><i>0</i>2.<i>0</i></em>[ÂæÍÕ¶Ó]ÕÙ¼¯Ê®Ò»¶ÓÓÑ¡¾°ÓÃÀ¡¿¡¾¶î¼Ã...</a></li>
+ <li><a href="http://p.infzm.com/link/72353" TARGET="_blank"><em><i>0</i>3.<i>0</i></em>µ±¡°·¨ÂÉ¡±³ÉΪõåõï°ÙÐյŤ¾ßʱ¡ª¡ªÆà...</a></li>
+
+ <li><a href="http://p.infzm.com/link/58459" TARGET="_blank"><em><i>0</i>4.<i>0</i></em>»¨2Äêʱ¼äÖÆ×÷µÄÒ»²¿9·ÖÖÓ¶ÌÆ¬</a></li>
+ <li><a href="http://p.infzm.com/link/85667" TARGET="_blank"><em><i>0</i>5.<i>0</i></em>µçÊÓ¹ºÎïµÄ±©ÀûÄÚÄ»</a></li>
+ <li><a href="http://p.infzm.com/link/60541" TARGET="_blank"><em><i>0</i>6.<i>0</i></em>һƬÎÀÉú½íÕü¾ÈÁËÈ«ÈËÀà</a></li>
+
+ <li><a href="http://p.infzm.com/link/57866" TARGET="_blank"><em><i>0</i>7.<i>0</i></em>Âò¸øÕÉĸÄïµÄ50ËêÉúÈÕµ°¸â¾¹×ö³ÉÁËÕâ...</a></li>
+ <li><a href="http://p.infzm.com/link/57544" TARGET="_blank"><em><i>0</i>8.<i>0</i></em>´©¶ÌÆìÅÛ¶´óÍÈ ÖÐʽ±ÏÒµÕÕÒý·¢ÍøÂç´ó...</a></li>
+ <li><a href="http://p.infzm.com/link/57451" TARGET="_blank"><em><i>0</i>9.<i>0</i></em>ÄÜÓÃÑó´Ð¸øiPod³äµçÂð£¿</a></li>
+
+ <li><a href="http://p.infzm.com/link/64989" TARGET="_blank"><em>10.<i>0</i></em>Ö´Õþµ³ÊÇ·ñÕæÕý´ú±íÁËÈËÃñÀûÒæ</a></li>
+ </ul>
+ <p class="more"><a class="rss" href="http://www.infzm.com/rss/home/rss2.0.xml">¶©ÔÄ</a><a href="http://p.infzm.com">¸ü¶à...</a></p>
+ </div>
+ <div class="footer">
+ <span id="f_t_id" class="footer_tab">
+ <a id="f_t_0" href="javascript:void(0)" onmouseover="showtopbytime(0)">µ±Ìì</a>
+ <a id="f_t_1" href="javascript:void(0)" onmouseover="showtopbytime(1)">7ÌìÄÚ</a>
+ <a id="f_t_2" href="javascript:void(0)" onmouseover="showtopbytime(2)">30ÌìÄÚ</a>
+ <a id="f_t_3" href="javascript:void(0)" onmouseover="showtopbytime(3)">ËùÓÐ</a>
+
+ </span>
+ </div>
+</div>
+<script>
+function showtopbytime( the_id )
+{
+ $ES("#f_t_id a").each(function(e){
+ if("f_t_"+the_id == e.id){
+ !e.hasClass( "curr" ) && e.addClass( "curr" );
+ } else {
+ e.removeClass( "curr" );
+ }
+ });
+
+ for ( var i=0; i < 4 ; i++) {
+ $('ul_'+top10_tab_nomber+'_'+i).setStyle( "display","none" );
+ }
+ $('ul_'+top10_tab_nomber+'_'+the_id).setStyle( "display","" );
+}
+</script> <div class="space h20"></div>
+ <div class="mm"></div>
+ <!--¶©ÔÄÖÐÐÄ-->
+ <!--<p><embed height="220" width="300" menu="true" loop="true" play="true" src="http://images.infzm.com/medias/2008/1231/20877.swf" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"></embed></p>-->
+<!--GOOGLE¹ã¸æ -->
+<div class="google_adv">
+</div><!--GOOGLE¹ã¸æEND-->
+
+ </div><!--end .grid_4-->
+ </div><!--end #contents-->
+ <div class="clear"></div>
+ </div>
+ <!--CONTENT END-->
+ <!--µ×²¿-->
+ <div id="footer">
+ <h3><a id="backTop" href="#">·µ»Ø¶¥²¿</a>ÄÏ·½ÖÜÄ©¹Ù·½ÍøÕ¾----www.infzm.com</h3>
+
+ <div id="footerNav" class="inner">
+ <div class="side-1">
+ <dl class="navList">
+ <dt><span class="a">·þÎñ</span></dt>
+ <dd><a href="http://group.infzm.com">ÄÏÖÜ´óÔº</a></dd>
+ <dd><a href="http://www.infzm.com/z.shtml">רÀ¸</a></dd>
+ <dd><a href="http://bbs.infzm.com">ÂÛ̳</a></dd>
+
+ <dd><a href="http://bbs.infzm.com/forumdisplay.php?fid=38">ÉÌÆ·</a></dd>
+ <dd class="noBor"><a href="">µç×Ó±¨¿¯</a></dd>
+ </dl>
+ <dl class="navList">
+ <dt><span class="b">×ÊѶ</span></dt>
+ <dd><a href="http://www.infzm.com/news.shtml">ÐÂÎÅ</a></dd>
+ <dd><a href="http://www.infzm.com/economy.shtml">¾¼Ã</a></dd>
+
+ <dd><a href="http://www.infzm.com/culture.shtml">ÎÄ»¯</a></dd>
+ <dd><a href="http://www.infzm.com/review.shtml">ÆÀÂÛ</a></dd>
+ <dd><a href="http://www.infzm.com/picture.shtml">ͼƬ</a></dd>
+ <dd class="noBor"><a href="http://www.infzm.com/fashion.shtml">Éú»î</a></dd>
+ </dl>
+ <dl class="navList red">
+ <dd class="first"><a href="http://www.infzm.com/rss/home/rss2.0.xml">RSS¶©ÔÄ</a></dd>
+
+ <dd><a href="">ÊÖ»ú±¨</a></dd>
+ <dd class="noBor"><a href="">¹ã¸æ</a></dd>
+ </dl>
+ </div>
+ <div class="side-2">
+ <dl class="navList">
+ <dt><span class="c"><a href="http://www.infzm.com/aboutus" target="_blank">¹ØÓÚÎÒÃÇ</a></span></dt>
+
+ <dd><a href="http://www.infzm.com/">infzm.com</a></dd>
+ <dd><a href="http://www.infzm.com/content/24164" target="_blank">ÄÏ·½ÖÜÄ©</a></dd>
+ <dd><a href="http://mangazine.infzm.com/" target="_blank">ÃûÅÆÔÓÖ¾</a></dd>
+ <dd class="noBor"><a href="http://www.infzm.com/nfrwzk/" target="_blank">ÄÏ·½ÈËÎïÖÜ¿¯</a></dd>
+ </dl>
+ <dl class="navList">
+ <dt><span class="d"><a href="http://www.infzm.com/event/">Æ·ÅÆ»î¶¯</a></span></dt>
+
+ <dd><a href="http://csr.infzm.com">ÄÏÖܹ«Òæ</a></dd>
+ <dd><a href="http://www.infzm.com/rich/">´´¸»¡¤500Ç¿</a></dd>
+ <dd class="noBor"><a href="http://www.infzm.com/topic/partnership.shtml">ºÏ×÷»ï°é</a></dd>
+ </dl>
+ <dl class="navList blue">
+ <dd class="first"><a href="http://www.infzm.com/topic/jobs.shtml" target="_blank">¼ÓÈëÎÒÃÇ</a></dd>
+ <dd class="first"><a href="http://z.infzm.com" target="_blank">¹Ù·½²©¿Í</a></dd>
+
+ <dd class="first"><a href="">Õ¾µãµØÍ¼</a></dd>
+ <dd><a href="http://www.infzm.com/aboutus/200803/t20080317_40300.htm" target="_blank">Óû§ÊØÔò</a></dd>
+ <dd class="noBor"><a href="">°æÈ¨ÉùÃ÷</a></dd>
+ </dl>
+ </div>
+ <div class="clear"></div>
+ </div>
+
+ <div class="inner Otherinfo">
+ <dl>
+ <dt>ÄÏ·½±¨Òµ´«Ã½¼¯ÍÅÖ÷°ì:</dt>
+ <dd><a href="http://www.nfdaily.cn/" target="_blank">ÄÏ·½ÈÕ±¨</a></dd>
+ <dd><a href="http://www.nanfangdaily.com.cn/southnews/dd/nc/" target="_blank">ÄÏ·½Å©´å±¨</a></dd>
+ <dd><a href="http://www.infzm.com">ÄÏ·½ÖÜÄ©</a></dd>
+ <dd><a href="http://www.nddaily.com/" target="_blank">ÄÏ·½¶¼Êб¨</a></dd>
+
+ <dd><a href="http://www.21cbh.com/" target="_blank">21ÊÀ¼Í¾¼Ã±¨µÀ</a></dd>
+ <dd><a href="http://www.thebeijingnews.com/" target="_blank">о©±¨</a></dd>
+ <dd><a href="http://www.xjrb.net" target="_blank">Î÷½ÈÕ±¨</a></dd>
+ <dd><a href="http://www.ynxxb.com/" target="_blank">ÔÆÄÏÐÅÏ¢±¨</a></dd>
+ <dd><a href="http://www.nbweekly.com/" target="_blank">Ä϶¼ÖÜ¿¯</a></dd>
+ <dd><a href="http://www.fengshangweekly.com/" target="_blank">·çÉÐÖܱ¨</a></dd>
+
+ <dd><a href="http://moneyweek.dooland.com/" target="_blank">Àí²ÆÖܱ¨</a></dd>
+ <dd><a href="http://www.nfyk.com/" target="_blank">ÄÏ·½</a></dd>
+ <dd class="secondline"><a href="http://www.nanfangdaily.com.cn/hb/20090428/" target="_blank">³ÇÊл±¨</a></dd>
+ <dd><a href="http://mangazine.infzm.com/" target="_blank">ÃûÅÆ</a></dd>
+ <dd><a href="http://www.infzm.com/nfrwzk/" target="_blank">ÄÏ·½ÈËÎïÖÜ¿¯</a></dd>
+ <dd><a href="http://www.21cbr.com/" target="_blank">21ÊÀ¼ÍÉÌÒµÆÀÂÛ</a></dd>
+
+ <dd><a href="" target="_blank">ÉÌÎñÂÃÐÐ</a></dd>
+ <dd><a href="http://www.southcn.com/" target="_blank">ÄÏ·½Íø</a></dd>
+ <dd><a href="http://www.nanfangdaily.com.cn/" target="_blank">ÄÏ·½±¨ÒµÍø</a></dd>
+ </dl>
+ <p><a href="http://www.southcn.com/">¹ã¶«ÄÏ·½ÍøÂçÐÅÏ¢¿Æ¼¼ÓÐÏÞ¹«Ë¾</a>¸ºÔðÖÆ×÷ά»¤ | ÐÂÎÅÐÅÏ¢·þÎñÐí¿ÉÖ¤ ICP¾ÓªÐí¿ÉÖ¤ºÅ£ºÔÁB2-20050235ºÅ</p>
+ </div>
+
+<div id="analytic">
+ <!--by google analytic-->
+ <script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
+ </script>
+ <script type="text/javascript">
+ _uacct = "UA-2915863-1";
+ urchinTracker();
+ </script>
+</div> </div><!--end #footer-->
+</div>
+</body>
+</html>
+
+</body>
+</html>
+
diff --git a/lib/index.html.data b/lib/index.html.data
new file mode 100644
index 0000000..c89e11c
--- /dev/null
+++ b/lib/index.html.data
@@ -0,0 +1,168 @@
+<select onchange="if(this.value !='') location=this.value">
+ <option value="http://www.infzm.com/enews/infzm/1321">20091001</option>
+ <option value="http://www.infzm.com/enews/infzm/1309">2009-09-24</option>
+ <option value="http://www.infzm.com/enews/infzm/1300">2009-09-17</option>
+ <option value="http://www.infzm.com/enews/infzm/1286">2009-09-10</option>
+ <option value="http://www.infzm.com/enews/infzm/1271">2009-09-03</option>
+ <option value="http://www.infzm.com/enews/infzm/1261">2009-08-27</option>
+
+ <option value="http://www.infzm.com/enews/infzm/1250">2009-08-20</option>
+ <option value="http://www.infzm.com/enews/infzm/1243">2009-08-13</option>
+ <option value="http://www.infzm.com/enews/infzm/1227">2009-08-06</option>
+ <option value="http://www.infzm.com/enews/infzm/1218">2009-07-30</option>
+ <option value="http://www.infzm.com/enews/infzm/1208">2009-07-23</option>
+ <option value="http://www.infzm.com/enews/infzm/1195">2009-07-16</option>
+
+ <option value="http://www.infzm.com/enews/infzm/1186">2009-07-09</option>
+ <option value="http://www.infzm.com/enews/infzm/1179">2009-07-02</option>
+ <option value="http://www.infzm.com/enews/infzm/1170">2009-06-25</option>
+ <option value="http://www.infzm.com/enews/infzm/1160">2009-06-18</option>
+ <option value="http://www.infzm.com/enews/infzm/1152">2009-06-11</option>
+ <option value="http://www.infzm.com/enews/infzm/1143">2009-06-04</option>
+
+ <option value="http://www.infzm.com/enews/infzm/1134">2009-05-28</option>
+ <option value="http://www.infzm.com/enews/infzm/1125">2009-05-21</option>
+ <option value="http://www.infzm.com/enews/infzm/1117">2009-05-14</option>
+ <option value="http://www.infzm.com/enews/infzm/1107">2009-05-07</option>
+ <option value="http://www.infzm.com/enews/infzm/1098">2009-04-30</option>
+ <option value="http://www.infzm.com/enews/infzm/1088">2009-04-23</option>
+
+ <option value="http://www.infzm.com/enews/infzm/1080">2009-04-16</option>
+ <option value="http://www.infzm.com/enews/infzm/1071">2009-04-09</option>
+ <option value="http://www.infzm.com/enews/infzm/1060">2009-04-02</option>
+ <option value="http://www.infzm.com/enews/infzm/1048">2009-03-26</option>
+ <option value="http://www.infzm.com/enews/infzm/1037">2009-03-19</option>
+ <option value="http://www.infzm.com/enews/infzm/1027">2009-03-12</option>
+
+ <option value="http://www.infzm.com/enews/infzm/1018">2009-03-05</option>
+ <option value="http://www.infzm.com/enews/infzm/999">2009-02-26</option>
+ <option value="http://www.infzm.com/enews/infzm/989">2009-02-19</option>
+ <option value="http://www.infzm.com/enews/infzm/977">2009-02-12</option>
+ <option value="http://www.infzm.com/enews/infzm/968">2009-02-05</option>
+ <option value="http://www.infzm.com/enews/infzm/955">2009-01-22</option>
+
+ <option value="http://www.infzm.com/enews/infzm/937">2009-01-15</option>
+ <option value="http://www.infzm.com/enews/infzm/928">2009-01-08</option>
+ <option value="http://www.infzm.com/enews/infzm/908">2009-01-01</option>
+ <option value="http://www.infzm.com/enews/infzm/896">2008-12-25</option>
+ <option value="http://www.infzm.com/enews/infzm/888">2008-12-18</option>
+ <option value="http://www.infzm.com/enews/infzm/877">2008-12-11</option>
+
+ <option value="http://www.infzm.com/enews/infzm/867">2008-12-04</option>
+ <option value="http://www.infzm.com/enews/infzm/850">2008-11-27</option>
+ <option value="http://www.infzm.com/enews/infzm/838">2008-11-20</option>
+ <option value="http://www.infzm.com/enews/infzm/836">2008-11-13</option>
+ <option value="http://www.infzm.com/enews/infzm/829">2008-11-06</option>
+ <option value="http://www.infzm.com/enews/infzm/794">2008-10-30</option>
+
+ <option value="http://www.infzm.com/enews/infzm/786">2008-10-23</option>
+ <option value="http://www.infzm.com/enews/infzm/777">2008-10-16</option>
+ <option value="http://www.infzm.com/enews/infzm/768">2008-10-09</option>
+ <option value="http://www.infzm.com/enews/infzm/760">2008-10-02</option>
+ <option value="http://www.infzm.com/enews/infzm/742">2008-09-25</option>
+ <option value="http://www.infzm.com/enews/infzm/731">2008-09-18</option>
+
+ <option value="http://www.infzm.com/enews/infzm/721">2008-09-11</option>
+ <option value="http://www.infzm.com/enews/infzm/713">2008-09-04</option>
+ <option value="http://www.infzm.com/enews/infzm/705">2008-08-28</option>
+ <option value="http://www.infzm.com/enews/infzm/694">2008-08-21</option>
+ <option value="http://www.infzm.com/enews/infzm/677">2008-08-14</option>
+ <option value="http://www.infzm.com/enews/infzm/665">2008-08-07</option>
+
+ <option value="http://www.infzm.com/enews/infzm/640">2008-07-31</option>
+ <option value="http://www.infzm.com/enews/infzm/633">2008-07-24</option>
+ <option value="http://www.infzm.com/enews/infzm/625">2008-07-17</option>
+ <option value="http://www.infzm.com/enews/infzm/618">2008-07-10</option>
+ <option value="http://www.infzm.com/enews/infzm/595">2008-07-03</option>
+ <option value="http://www.infzm.com/enews/infzm/584">2008-06-26</option>
+
+ <option value="http://www.infzm.com/enews/infzm/575">2008-06-19</option>
+ <option value="http://www.infzm.com/enews/infzm/558">2008-06-12</option>
+ <option value="http://www.infzm.com/enews/infzm/546">2008-06-05</option>
+ <option value="http://www.infzm.com/enews/infzm/530">2008-05-29</option>
+ <option value="http://www.infzm.com/enews/infzm/524">2008-05-22</option>
+ <option value="http://www.infzm.com/enews/infzm/501">2008-05-15</option>
+
+ <option value="http://www.infzm.com/enews/infzm/509">2008-05-14</option>
+ <option value="http://www.infzm.com/enews/infzm/490">2008-05-08</option>
+ <option value="http://www.infzm.com/enews/infzm/218">2008-05-01</option>
+ <option value="http://www.infzm.com/enews/infzm/201">2008-04-24</option>
+ <option value="http://www.infzm.com/enews/infzm/37">2008-04-17</option>
+ <option value="http://www.infzm.com/enews/infzm/20">2008-04-10</option>
+
+ <option value="http://www.infzm.com/enews/infzm/177">2008-04-03</option>
+ <option value="http://www.infzm.com/enews/infzm/84">2008-03-27</option>
+ <option value="http://www.infzm.com/enews/infzm/129">2008-03-20</option>
+ <option value="http://www.infzm.com/enews/infzm/190">2008-03-13</option>
+ <option value="http://www.infzm.com/enews/infzm/66">2008-03-06</option>
+ <option value="http://www.infzm.com/enews/infzm/39">2008-02-28</option>
+
+ <option value="http://www.infzm.com/enews/infzm/166">2008-02-21</option>
+ <option value="http://www.infzm.com/enews/infzm/48">2008-02-14</option>
+ <option value="http://www.infzm.com/enews/infzm/55">2008-02-07</option>
+ <option value="http://www.infzm.com/enews/infzm/155">2008-01-31</option>
+ <option value="http://www.infzm.com/enews/infzm/171">2008-01-24</option>
+ <option value="http://www.infzm.com/enews/infzm/198">2008-01-17</option>
+
+ <option value="http://www.infzm.com/enews/infzm/17">2008-01-10</option>
+ <option value="http://www.infzm.com/enews/infzm/149">2008-01-03</option>
+ <option value="http://www.infzm.com/enews/infzm/143">2007-12-27</option>
+ <option value="http://www.infzm.com/enews/infzm/73">2007-12-20</option>
+ <option value="http://www.infzm.com/enews/infzm/195">2007-12-13</option>
+ <option value="http://www.infzm.com/enews/infzm/137">2007-12-06</option>
+
+ <option value="http://www.infzm.com/enews/infzm/210">2007-11-29</option>
+ <option value="http://www.infzm.com/enews/infzm/80">2007-11-22</option>
+ <option value="http://www.infzm.com/enews/infzm/106">2007-11-15</option>
+ <option value="http://www.infzm.com/enews/infzm/110">2007-11-08</option>
+ <option value="http://www.infzm.com/enews/infzm/113">2007-11-01</option>
+ <option value="http://www.infzm.com/enews/infzm/100">2007-10-25</option>
+
+ <option value="http://www.infzm.com/enews/infzm/134">2007-10-18</option>
+ <option value="http://www.infzm.com/enews/infzm/56">2007-10-11</option>
+ <option value="http://www.infzm.com/enews/infzm/35">2007-10-04</option>
+ <option value="http://www.infzm.com/enews/infzm/207">2007-09-27</option>
+ <option value="http://www.infzm.com/enews/infzm/60">2007-09-20</option>
+ <option value="http://www.infzm.com/enews/infzm/204">2007-09-13</option>
+
+ <option value="http://www.infzm.com/enews/infzm/31">2007-09-06</option>
+ <option value="http://www.infzm.com/enews/infzm/192">2007-08-30</option>
+ <option value="http://www.infzm.com/enews/infzm/213">2007-08-23</option>
+ <option value="http://www.infzm.com/enews/infzm/168">2007-08-16</option>
+ <option value="http://www.infzm.com/enews/infzm/132">2007-08-09</option>
+ <option value="http://www.infzm.com/enews/infzm/63">2007-08-02</option>
+
+ <option value="http://www.infzm.com/enews/infzm/186">2007-07-26</option>
+ <option value="http://www.infzm.com/enews/infzm/188">2007-07-19</option>
+ <option value="http://www.infzm.com/enews/infzm/146">2007-07-12</option>
+ <option value="http://www.infzm.com/enews/infzm/97">2007-07-05</option>
+ <option value="http://www.infzm.com/enews/infzm/164">2007-06-28</option>
+ <option value="http://www.infzm.com/enews/infzm/182">2007-06-21</option>
+
+ <option value="http://www.infzm.com/enews/infzm/95">2007-06-14</option>
+ <option value="http://www.infzm.com/enews/infzm/76">2007-06-07</option>
+ <option value="http://www.infzm.com/enews/infzm/179">2007-05-31</option>
+ <option value="http://www.infzm.com/enews/infzm/159">2007-05-24</option>
+ <option value="http://www.infzm.com/enews/infzm/90">2007-05-17</option>
+ <option value="http://www.infzm.com/enews/infzm/24">2007-05-10</option>
+
+ <option value="http://www.infzm.com/enews/infzm/127">2007-05-03</option>
+ <option value="http://www.infzm.com/enews/infzm/93">2007-04-26</option>
+ <option value="http://www.infzm.com/enews/infzm/70">2007-04-19</option>
+ <option value="http://www.infzm.com/enews/infzm/103">2007-04-12</option>
+ <option value="http://www.infzm.com/enews/infzm/141">2007-04-05</option>
+ <option value="http://www.infzm.com/enews/infzm/122">2007-03-29</option>
+
+ <option value="http://www.infzm.com/enews/infzm/139">2007-03-22</option>
+ <option value="http://www.infzm.com/enews/infzm/28">2007-03-15</option>
+ <option value="http://www.infzm.com/enews/infzm/152">2007-03-08</option>
+ <option value="http://www.infzm.com/enews/infzm/115">2007-03-01</option>
+ <option value="http://www.infzm.com/enews/infzm/86">2007-02-22</option>
+ <option value="http://www.infzm.com/enews/infzm/161">2007-02-15</option>
+
+ <option value="http://www.infzm.com/enews/infzm/108">2007-02-08</option>
+ <option value="http://www.infzm.com/enews/infzm/124">2007-02-01</option>
+ <option value="http://www.infzm.com/enews/infzm/174">2007-01-25</option>
+ <option value="http://www.infzm.com/enews/infzm/52">2007-01-18</option>
+ <option value="http://www.infzm.com/enews/infzm/43">2007-01-11</option>
+ <option value="http://www.infzm.com/enews/infzm/119">2007-01-04</option>
diff --git a/lib/j.html.data b/lib/j.html.data
new file mode 100644
index 0000000..b531ce0
--- /dev/null
+++ b/lib/j.html.data
@@ -0,0 +1,564 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+ <title>ÄÏ·½ÖÜÄ©</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+ <meta name="keywords" content="ÄÏ·½ÖÜÄ©±¨ ÄÏ·½ÖÜÄ©ÍøÕ¾ ÄÏ·½ÖÜÄ©¹Ù·½ÍøÕ¾ ÄÏ·½ÖÜÄ©µç×Ó°æ ÂÛ̳ ÉçÇø ÔÚÏßÔĶÁ ÐÂÎÅÏßË÷ ¶ÁÕß" />
+ <meta name="description" content="www.infzm.com£¬ÄÏ·½ÖÜÄ©ÐÂÎÅÉçÇø" />
+ <link rel="stylesheet" type="text/css" href="http://images.infzm.com/css/2009/header.css" />
+ <link rel="stylesheet" type="text/css" href="http://images.infzm.com/css/2009/footer.css" />
+ <link rel="stylesheet" type="text/css" href="http://images.infzm.com/css/2009/enews_style.css" />
+sdf
+ <script type="text/javascript" src="http://www.infzm.com/js/mootools-min.js"></script>
+ <script type="text/javascript" src="http://www.infzm.com/2008/js/header.js"></script>
+ <script type="text/javascript" src="http://passport.infzm.com/passport/ssologinform/raw?container=userPanel&style=top"></script>
+ </head>
+<body>
+ <div id="header">
+<div id="userPanel" class="noUserIcon"></div><!--Óû§×´Ì¬À¸-->
+<div id="left">
+ <a href="http://www.infzm.com" id="siteLogo" title="ÄÏ·½ÖÜÄ©ÍøÕ¾ www.infzm.com"></a>
+
+ <div id="header-media">
+ <!--top-->
+ <p> </p>
+<p><a href="http://www.infzm.com/enews/infzm"><img src="http://images.infzm.com/medias/2009/0930/30820.png" alt="" /><br />
+</a></p> <!--end top -->
+ </div>
+</div>
+<div id="right">
+<h3>ÄÏ·½ÖÜÄ©±¨ÏµÆìÏÂýÌå</h3>
+<a href="http://www.infzm.com/25years.shtml" target="_blank"><div class="nfzm-toplogo"></div></a>
+<a href="http://mangazine.infzm.com" target="_blank"><div class="mangazine-toplogo"></div></a>
+
+<a href="http://www.infzm.com/enews/nfrwzk" target="_blank"><div class="nfrw-toplogo"></div></a>
+</div>
+ <div class="clear"></div>
+ <div id="NavSearchBar">
+ <div id="main-nav"><ul>
+ <li id="home-nav" class="action"><a href="http://www.infzm.com">Ê×Ò³</a></li>
+ <li id="blog-nav" class=""><a href="http://www.infzm.com/z.shtml">רÀ¸</a></li>
+<!-- <li id="digg-nav" class=""><a href="http://p.infzm.com">ÍøÕª</a></li>-->
+ <li id="group-nav" class=""><a href="http://group.infzm.com">ÄÏÖÜ´óÔº <font style="color:#c00;font-size:14px">New</font></a></li>
+
+ <li id="tag-nav" class=""><a href="http://tags.infzm.com">±êÇ©</a></li>
+ <li id="bbs" class=""><a href="http://bbs.infzm.com">ÂÛ̳</a></li>
+ <li id="vote-nav" class=""><a href="http://www.infzm.com/vote.shtml">Ãñµ÷ÖÐÐÄ</a></li>
+ <li id="voice"><a href="http://www.infzm.com/voice">ååÓÐÉù</a></li>
+ </ul></div>
+ <div id="search">
+ <span class="tt">ËÑË÷</span>
+
+ <form method="get" action="http://www.infzm.com/search.php" target="_top" id="SearchForm">
+ <input type="hidden" name="domains" value="infzm.com"></input>
+ <input type="hidden" name="sitesearch" value="infzm.com"></input>
+ <input type="hidden" name="client" value="pub-9592521274658723"></input>
+ <input type="hidden" name="forid" value="1"></input>
+ <input type="hidden" name="ie" value="utf-8"></input>
+ <input type="hidden" name="oe" value="utf-8"></input>
+ <input type="hidden" name="cof" value="GALT:#2D8930;GL:1;DIV:#FFFFFF;VLC:CC0000;AH:center;BGC:FFFFFF;LBGC:FFFFFF;ALC:0066CC;LC:0066CC;T:808080;GFNT:99C9FF;GIMP:99C9FF;LH:40;LW:100;L:http://www.infzm.com/images/infzm_logo_0708.gif;S:http://www.infzm.com;LP:1;FORID:11"></input>
+ <input type="hidden" name="hl" value="zh-CN"></input>
+
+ <span class="input"><input type="text" name="q" value="" /></span>
+ <span class="submit"><input type="image" src="http://www.infzm.com/2008/images/search-submit.png" /></span>
+ </form>
+ </div>
+ </div>
+<div id="main-sub-nav">
+ <ul id="home-nav-sub">
+ <li><a href="http://www.infzm.com/news.shtml" class="">ÐÂÎÅ</a></li>
+ <li><a href="http://www.infzm.com/economy.shtml" class="">¾¼Ã</a></li>
+
+ <li><a href="http://www.infzm.com/culture.shtml" class="">ÎÄ»¯</a></li>
+ <li><a href="http://www.infzm.com/review.shtml" class="">ÆÀÂÛ</a></li>
+ <li><a href="http://www.infzm.com/fashion.shtml" class="">Éú»î</a></li>
+ <li><a href="http://www.infzm.com/image.shtml" class="">ͼƬ</a></li>
+ </ul>
+ <script type="text/javascript">
+
+var bulletin_alternater = {
+ target : "postboard",
+ height : 16,
+ total : 4,
+ current : 0,
+ interval : 5000,
+ enabled : true,
+ effect : null,
+ start : function() {
+ this.effect = new Fx.Scroll( this.target );
+ bulletin_alternater.run.periodical( this.interval, bulletin_alternater );
+ },
+ run : function () {
+ if ( this.enabled == false ) return;
+
+ if ( this.current > this.total )
+ this.current = 0;
+
+ this.effect.scrollTo( 0, this.current * this.height );
+
+ this.current ++;
+ },
+ enable : function () {
+ bulletin_alternater.enabled = true;
+ },
+ disable : function () {
+ bulletin_alternater.enabled = false;
+ }
+};
+
+window.addEvent("domready",function(){
+ $("postboard").addEvent("mouseenter",bulletin_alternater.disable);
+ $("postboard").addEvent("mouseleave",bulletin_alternater.enable);
+ bulletin_alternater.start();
+});
+</script>
+
+<div id="postboard" >
+ <ul>
+ <li><a href="http://www.infzm.com/contents/434">ÄÏÖܹ«¸æ</a>>> <a class="bulletin" href="http://www.infzm.com/content/35680">gphone°æÄÏÖÜÔĶÁÆ÷·¢²¼£¬»¶Ó´ó...</a></li>
+ <li><a href="http://www.infzm.com/contents/434">ÄÏÖܹ«¸æ</a>>> <a class="bulletin" href="http://www.infzm.com/content/34319">»¶ÓÊÔÓÃMSN¶©ÔÄ¡¶ÄÏ·½ÖÜÄ©¡·</a></li>
+ <li><a href="http://www.infzm.com/contents/434">ÄÏÖܹ«¸æ</a>>> <a class="bulletin" href="http://www.infzm.com/content/34286">¡¶ÄÏ·½ÖÜÄ©¡·¾¼Ã²¿ÕÐÊÕʵϰÉú</a></li>
+ <li><a href="http://www.infzm.com/contents/434">ÄÏÖܹ«¸æ</a>>> <a class="bulletin" href="http://www.infzm.com/content/33934">ÄÏ·½ÖÜÄ©ÍøÊµÏ°ÉúÕÐÆ¸</a></li>
+
+ <li><a href="http://www.infzm.com/contents/434">ÄÏÖܹ«¸æ</a>>> <a class="bulletin" href="http://www.infzm.com/content/33338">ÄÏ·½ÖÜÄ©¹Ù·½Î¢²©¿Í´ó¹«¿ª</a></li>
+ </ul>
+</div>
+</div>
+</div> <div id="wrap">
+ <!--CONTENT BEGIN-->
+ ?<!--Ö÷Ìå-->
+ <div id="contents">
+
+ <div id="enews_header">
+ <h1>
+ <span>µç×Ó±¨¿¯>></span>ÄÏ·½ÖÜÄ© </h1>
+ </div>
+ <div class="inner col-2lb" id="enews_index">
+
+ <div class="side-1">
+ <div class="cover">
+
+ <img width="180" src="http://images.infzm.com/medias/2009/0930/30819.jpeg"/>
+
+ <p>2009Äê10ÔÂ8ÈÕ</p>
+ <p>µÚ1338ÆÚ</p>
+ <strong>
+ <span class="f14">ÍùÆÚ</span>
+ <select onchange="if(this.value !='') location=this.value">
+ <option>Ñ¡ÔñÈÕÆÚ</option>
+
+ <option value="http://www.infzm.com/enews/infzm/1321">20091001</option>
+ <option value="http://www.infzm.com/enews/infzm/1309">2009-09-24</option>
+ <option value="http://www.infzm.com/enews/infzm/1300">2009-09-17</option>
+ <option value="http://www.infzm.com/enews/infzm/1286">2009-09-10</option>
+ <option value="http://www.infzm.com/enews/infzm/1271">2009-09-03</option>
+ <option value="http://www.infzm.com/enews/infzm/1261">2009-08-27</option>
+
+ <option value="http://www.infzm.com/enews/infzm/1250">2009-08-20</option>
+ <option value="http://www.infzm.com/enews/infzm/1243">2009-08-13</option>
+ <option value="http://www.infzm.com/enews/infzm/1227">2009-08-06</option>
+ <option value="http://www.infzm.com/enews/infzm/1218">2009-07-30</option>
+ <option value="http://www.infzm.com/enews/infzm/1208">2009-07-23</option>
+ <option value="http://www.infzm.com/enews/infzm/1195">2009-07-16</option>
+
+ <option value="http://www.infzm.com/enews/infzm/1186">2009-07-09</option>
+ <option value="http://www.infzm.com/enews/infzm/1179">2009-07-02</option>
+ <option value="http://www.infzm.com/enews/infzm/1170">2009-06-25</option>
+ <option value="http://www.infzm.com/enews/infzm/1160">2009-06-18</option>
+ <option value="http://www.infzm.com/enews/infzm/1152">2009-06-11</option>
+ <option value="http://www.infzm.com/enews/infzm/1143">2009-06-04</option>
+
+ <option value="http://www.infzm.com/enews/infzm/1134">2009-05-28</option>
+ <option value="http://www.infzm.com/enews/infzm/1125">2009-05-21</option>
+ <option value="http://www.infzm.com/enews/infzm/1117">2009-05-14</option>
+ <option value="http://www.infzm.com/enews/infzm/1107">2009-05-07</option>
+ <option value="http://www.infzm.com/enews/infzm/1098">2009-04-30</option>
+ <option value="http://www.infzm.com/enews/infzm/1088">2009-04-23</option>
+
+ <option value="http://www.infzm.com/enews/infzm/1080">2009-04-16</option>
+ <option value="http://www.infzm.com/enews/infzm/1071">2009-04-09</option>
+ <option value="http://www.infzm.com/enews/infzm/1060">2009-04-02</option>
+ <option value="http://www.infzm.com/enews/infzm/1048">2009-03-26</option>
+ <option value="http://www.infzm.com/enews/infzm/1037">2009-03-19</option>
+ <option value="http://www.infzm.com/enews/infzm/1027">2009-03-12</option>
+
+ <option value="http://www.infzm.com/enews/infzm/1018">2009-03-05</option>
+ <option value="http://www.infzm.com/enews/infzm/999">2009-02-26</option>
+ <option value="http://www.infzm.com/enews/infzm/989">2009-02-19</option>
+ <option value="http://www.infzm.com/enews/infzm/977">2009-02-12</option>
+ <option value="http://www.infzm.com/enews/infzm/968">2009-02-05</option>
+ <option value="http://www.infzm.com/enews/infzm/955">2009-01-22</option>
+
+ <option value="http://www.infzm.com/enews/infzm/937">2009-01-15</option>
+ <option value="http://www.infzm.com/enews/infzm/928">2009-01-08</option>
+ <option value="http://www.infzm.com/enews/infzm/908">2009-01-01</option>
+ <option value="http://www.infzm.com/enews/infzm/896">2008-12-25</option>
+ <option value="http://www.infzm.com/enews/infzm/888">2008-12-18</option>
+ <option value="http://www.infzm.com/enews/infzm/877">2008-12-11</option>
+
+ <option value="http://www.infzm.com/enews/infzm/867">2008-12-04</option>
+ <option value="http://www.infzm.com/enews/infzm/850">2008-11-27</option>
+ <option value="http://www.infzm.com/enews/infzm/838">2008-11-20</option>
+ <option value="http://www.infzm.com/enews/infzm/836">2008-11-13</option>
+ <option value="http://www.infzm.com/enews/infzm/829">2008-11-06</option>
+ <option value="http://www.infzm.com/enews/infzm/794">2008-10-30</option>
+
+ <option value="http://www.infzm.com/enews/infzm/786">2008-10-23</option>
+ <option value="http://www.infzm.com/enews/infzm/777">2008-10-16</option>
+ <option value="http://www.infzm.com/enews/infzm/768">2008-10-09</option>
+ <option value="http://www.infzm.com/enews/infzm/760">2008-10-02</option>
+ <option value="http://www.infzm.com/enews/infzm/742">2008-09-25</option>
+ <option value="http://www.infzm.com/enews/infzm/731">2008-09-18</option>
+
+ <option value="http://www.infzm.com/enews/infzm/721">2008-09-11</option>
+ <option value="http://www.infzm.com/enews/infzm/713">2008-09-04</option>
+ <option value="http://www.infzm.com/enews/infzm/705">2008-08-28</option>
+ <option value="http://www.infzm.com/enews/infzm/694">2008-08-21</option>
+ <option value="http://www.infzm.com/enews/infzm/677">2008-08-14</option>
+ <option value="http://www.infzm.com/enews/infzm/665">2008-08-07</option>
+
+ <option value="http://www.infzm.com/enews/infzm/640">2008-07-31</option>
+ <option value="http://www.infzm.com/enews/infzm/633">2008-07-24</option>
+ <option value="http://www.infzm.com/enews/infzm/625">2008-07-17</option>
+ <option value="http://www.infzm.com/enews/infzm/618">2008-07-10</option>
+ <option value="http://www.infzm.com/enews/infzm/595">2008-07-03</option>
+ <option value="http://www.infzm.com/enews/infzm/584">2008-06-26</option>
+
+ <option value="http://www.infzm.com/enews/infzm/575">2008-06-19</option>
+ <option value="http://www.infzm.com/enews/infzm/558">2008-06-12</option>
+ <option value="http://www.infzm.com/enews/infzm/546">2008-06-05</option>
+ <option value="http://www.infzm.com/enews/infzm/530">2008-05-29</option>
+ <option value="http://www.infzm.com/enews/infzm/524">2008-05-22</option>
+ <option value="http://www.infzm.com/enews/infzm/501">2008-05-15</option>
+
+ <option value="http://www.infzm.com/enews/infzm/509">2008-05-14</option>
+ <option value="http://www.infzm.com/enews/infzm/490">2008-05-08</option>
+ <option value="http://www.infzm.com/enews/infzm/218">2008-05-01</option>
+ <option value="http://www.infzm.com/enews/infzm/201">2008-04-24</option>
+ <option value="http://www.infzm.com/enews/infzm/37">2008-04-17</option>
+ <option value="http://www.infzm.com/enews/infzm/20">2008-04-10</option>
+
+ <option value="http://www.infzm.com/enews/infzm/177">2008-04-03</option>
+ <option value="http://www.infzm.com/enews/infzm/84">2008-03-27</option>
+ <option value="http://www.infzm.com/enews/infzm/129">2008-03-20</option>
+ <option value="http://www.infzm.com/enews/infzm/190">2008-03-13</option>
+ <option value="http://www.infzm.com/enews/infzm/66">2008-03-06</option>
+ <option value="http://www.infzm.com/enews/infzm/39">2008-02-28</option>
+
+ <option value="http://www.infzm.com/enews/infzm/166">2008-02-21</option>
+ <option value="http://www.infzm.com/enews/infzm/48">2008-02-14</option>
+ <option value="http://www.infzm.com/enews/infzm/55">2008-02-07</option>
+ <option value="http://www.infzm.com/enews/infzm/155">2008-01-31</option>
+ <option value="http://www.infzm.com/enews/infzm/171">2008-01-24</option>
+ <option value="http://www.infzm.com/enews/infzm/198">2008-01-17</option>
+
+ <option value="http://www.infzm.com/enews/infzm/17">2008-01-10</option>
+ <option value="http://www.infzm.com/enews/infzm/149">2008-01-03</option>
+ <option value="http://www.infzm.com/enews/infzm/143">2007-12-27</option>
+ <option value="http://www.infzm.com/enews/infzm/73">2007-12-20</option>
+ <option value="http://www.infzm.com/enews/infzm/195">2007-12-13</option>
+ <option value="http://www.infzm.com/enews/infzm/137">2007-12-06</option>
+
+ <option value="http://www.infzm.com/enews/infzm/210">2007-11-29</option>
+ <option value="http://www.infzm.com/enews/infzm/80">2007-11-22</option>
+ <option value="http://www.infzm.com/enews/infzm/106">2007-11-15</option>
+ <option value="http://www.infzm.com/enews/infzm/110">2007-11-08</option>
+ <option value="http://www.infzm.com/enews/infzm/113">2007-11-01</option>
+ <option value="http://www.infzm.com/enews/infzm/100">2007-10-25</option>
+
+ <option value="http://www.infzm.com/enews/infzm/134">2007-10-18</option>
+ <option value="http://www.infzm.com/enews/infzm/56">2007-10-11</option>
+ <option value="http://www.infzm.com/enews/infzm/35">2007-10-04</option>
+ <option value="http://www.infzm.com/enews/infzm/207">2007-09-27</option>
+ <option value="http://www.infzm.com/enews/infzm/60">2007-09-20</option>
+ <option value="http://www.infzm.com/enews/infzm/204">2007-09-13</option>
+
+ <option value="http://www.infzm.com/enews/infzm/31">2007-09-06</option>
+ <option value="http://www.infzm.com/enews/infzm/192">2007-08-30</option>
+ <option value="http://www.infzm.com/enews/infzm/213">2007-08-23</option>
+ <option value="http://www.infzm.com/enews/infzm/168">2007-08-16</option>
+ <option value="http://www.infzm.com/enews/infzm/132">2007-08-09</option>
+ <option value="http://www.infzm.com/enews/infzm/63">2007-08-02</option>
+
+ <option value="http://www.infzm.com/enews/infzm/186">2007-07-26</option>
+ <option value="http://www.infzm.com/enews/infzm/188">2007-07-19</option>
+ <option value="http://www.infzm.com/enews/infzm/146">2007-07-12</option>
+ <option value="http://www.infzm.com/enews/infzm/97">2007-07-05</option>
+ <option value="http://www.infzm.com/enews/infzm/164">2007-06-28</option>
+ <option value="http://www.infzm.com/enews/infzm/182">2007-06-21</option>
+
+ <option value="http://www.infzm.com/enews/infzm/95">2007-06-14</option>
+ <option value="http://www.infzm.com/enews/infzm/76">2007-06-07</option>
+ <option value="http://www.infzm.com/enews/infzm/179">2007-05-31</option>
+ <option value="http://www.infzm.com/enews/infzm/159">2007-05-24</option>
+ <option value="http://www.infzm.com/enews/infzm/90">2007-05-17</option>
+ <option value="http://www.infzm.com/enews/infzm/24">2007-05-10</option>
+
+ <option value="http://www.infzm.com/enews/infzm/127">2007-05-03</option>
+ <option value="http://www.infzm.com/enews/infzm/93">2007-04-26</option>
+ <option value="http://www.infzm.com/enews/infzm/70">2007-04-19</option>
+ <option value="http://www.infzm.com/enews/infzm/103">2007-04-12</option>
+ <option value="http://www.infzm.com/enews/infzm/141">2007-04-05</option>
+ <option value="http://www.infzm.com/enews/infzm/122">2007-03-29</option>
+
+ <option value="http://www.infzm.com/enews/infzm/139">2007-03-22</option>
+ <option value="http://www.infzm.com/enews/infzm/28">2007-03-15</option>
+ <option value="http://www.infzm.com/enews/infzm/152">2007-03-08</option>
+ <option value="http://www.infzm.com/enews/infzm/115">2007-03-01</option>
+ <option value="http://www.infzm.com/enews/infzm/86">2007-02-22</option>
+ <option value="http://www.infzm.com/enews/infzm/161">2007-02-15</option>
+
+ <option value="http://www.infzm.com/enews/infzm/108">2007-02-08</option>
+ <option value="http://www.infzm.com/enews/infzm/124">2007-02-01</option>
+ <option value="http://www.infzm.com/enews/infzm/174">2007-01-25</option>
+ <option value="http://www.infzm.com/enews/infzm/52">2007-01-18</option>
+ <option value="http://www.infzm.com/enews/infzm/43">2007-01-11</option>
+ <option value="http://www.infzm.com/enews/infzm/119">2007-01-04</option>
+
+ </select>
+ </strong>
+ </div>
+ <ul id="otherEnews">
+ <li><a href="http://www.infzm.com/enews/magazine">ÃûÅÆÔÓÖ¾</a></li>
+ <li><a href="http://www.infzm.com/enews/nfrwzk">ÄÏ·½ÈËÎïÖÜ¿¯</a></li>
+ </ul>
+ <p style="margin-left: 10px;"><a href="http://bbs.infzm.com/trade.php?tid=21727&pid=182496">¡¡</a></p><!--google¹ã¸æ--><div class="google_adv">
+
+<span><script type='text/javascript'><!--// <![CDATA[
+/* openads=http://x.infzm.com/www/delivery bannerid=14 zoneid=33 source= */
+// ]]> --></script><script type="text/javascript"><!--
+google_ad_client = "pub-9592521274658723";
+/* 160x600, µç×Ó±¨-ÄÏ·½ÖÜÄ©-Ŀ¼ */
+google_ad_slot = "6253066670";
+google_ad_width = 160;
+google_ad_height = 600;
+//-->
+</script>
+<script type="text/javascript"
+src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
+</script><script type='text/javascript' src='http://x.infzm.com/www/delivery/ag.php'></script></span><div id='beacon_1d789c0820' style='position: absolute; left: 0px; top: 0px; visibility: hidden;'><img src='http://x.infzm.com/www/delivery/lg.php?bannerid=14&campaignid=13&zoneid=33&loc=1&referer=http%3A%2F%2Fwww.infzm.com%2Fenews%2Finfzm&cb=1d789c0820' width='0' height='0' alt='' style='width: 0px; height: 0px;' /></div></div><!--google¹ã¸æEND-->
+
+ </div>
+ <div class="side-2">
+ <dl class="topnews">
+ <dt><span>±¾ÆÚÍ·Ìõ:</span><a href="http://www.infzm.com/content/35679" title="¹û¸ÒÓàÉú">¹û¸ÒÓàÉú</a>
+ </dt>
+
+ <dd class="summary">Ãå±±¾üʳåÍ»ºó»ªÈËÉú´æ×´Ì¬¹Û²ì£ºÖйúÊÇËûÃÇΩһµÄÏ£Íû</dd>
+ </dl>
+
+ <div class="left">
+ <h2>¾¼Ã</h2>
+ <dl>
+ <dt></dt>
+ <dd>
+
+ <ul class="relnews">
+ <li><a href="http://www.infzm.com/content/35661" title="¸£½¨ÉϺ¼ÏØ£ºÇ¦Öж¾¿Ö»ÅÖ®ºó">¸£½¨ÉϺ¼ÏØ£ºÇ¦Öж¾¿Ö»ÅÖ®ºó</a></li>
+ <li><a href="http://www.infzm.com/content/35635" title="ס·¿ÊÇÖйúÈË×î´óµÄ¼ÒÍ¥²Æ¸»">ס·¿ÊÇÖйúÈË×î´óµÄ¼ÒÍ¥²Æ¸»</a></li>
+ <li><a href="http://www.infzm.com/content/35636" title="¿çÔ½ÖйúÖÆÔ죬ÎÒÃǸÃÏòÈÕ±¾È¡Ê²Ã´¾?¡ª¡ª×¨·ÃÈÕ±¾Õ½ÂÔÖ®¸¸¡¢¹ÜÀíѧ¼Ò´óǰÑÐÒ»">¿çÔ½ÖйúÖÆÔ죬ÎÒÃǸÃÏòÈÕ±¾È¡Ê²Ã´¾?¡ª¡ª×¨·ÃÈÕ±¾...</a></li>
+ <li><a href="http://www.infzm.com/content/35637" title="Æ·ÅÆ£¬ÔÚ·ì϶Öн¥½ø¡ª¡ªº£¶ûµÄº£Íâ¹ÊÊÂ">Æ·ÅÆ£¬ÔÚ·ì϶Öн¥½ø¡ª¡ªº£¶ûµÄº£Íâ¹ÊÊÂ</a></li>
+ <li><a href="http://www.infzm.com/content/35638" title="Öйú¿ó²ú×ÊÔ´²úȨÓë¼Û¸ñÖÆ¶ÈµÄ60Äê±äǨ">Öйú¿ó²ú×ÊÔ´²úȨÓë¼Û¸ñÖÆ¶ÈµÄ60Äê±äǨ</a></li>
+
+ <li><a href="http://www.infzm.com/content/35639" title="¸»ºÀÃÇÀ´×Ժδ¦¡ª¡ªÖжíÐÙÈý¹ú¸»ºÀ°ñÖ®±È½Ï">¸»ºÀÃÇÀ´×Ժδ¦¡ª¡ªÖжíÐÙÈý¹ú¸»ºÀ°ñÖ®±È½Ï</a></li>
+ </ul>
+ </dd>
+ </dl>
+ <h2>ÆÀÂÛ</h2>
+ <dl>
+ <dt></dt>
+ <dd>
+
+ <ul class="relnews">
+ <li><a href="http://www.infzm.com/content/35662" title="¡¾ÎÄ»¯½âÂë¡¿Íøñ«ÊDz»ÊÇÒ»ÖÖñ«">¡¾ÎÄ»¯½âÂë¡¿Íøñ«ÊDz»ÊÇÒ»ÖÖñ«</a></li>
+ <li><a href="http://www.infzm.com/content/35663" title="Ìáʾ¡°ÎÂܰ¡±ÔÚÄÄÀï">Ìáʾ¡°ÎÂܰ¡±ÔÚÄÄÀï</a></li>
+ <li><a href="http://www.infzm.com/content/35664" title="¡¾Ë¼ÏëÓÎÄÁ¡¿ÄãµÃÀûÈó£¬ÎÒÀ´Âñµ¥">¡¾Ë¼ÏëÓÎÄÁ¡¿ÄãµÃÀûÈó£¬ÎÒÀ´Âñµ¥</a></li>
+ <li><a href="http://www.infzm.com/content/35666" title="¡¾·ÅÑÔËĺ£¡¿ºô»½ÂÌÉ«GDP">¡¾·ÅÑÔËĺ£¡¿ºô»½ÂÌÉ«GDP</a></li>
+ <li><a href="http://www.infzm.com/content/35667" title="¡¾¹«ÃñѲÊÓ¡¿Ì¨Íå¡°´ó¼Ò³¤¡±¾Éµ××Ó»¹ÔÚ">¡¾¹«ÃñѲÊÓ¡¿Ì¨Íå¡°´ó¼Ò³¤¡±¾Éµ××Ó»¹ÔÚ</a></li>
+
+ <li><a href="http://www.infzm.com/content/35668" title="¡¾Éç»á°ÑÂö¡¿²»¿É˼ÒéµÄÖйúÈË£¨Ö®Ò»£©">¡¾Éç»á°ÑÂö¡¿²»¿É˼ÒéµÄÖйúÈË£¨Ö®Ò»£©</a></li>
+ </ul>
+ </dd>
+ </dl>
+ <h2>ÐÂÎÅ</h2>
+ <dl>
+ <dt></dt>
+ <dd>
+
+ <ul class="relnews">
+ <li><a href="http://www.infzm.com/content/35665" title="¡¾Î¹Ê֪С¿Ê²Ã´Äñ¶¼ÓеÄÊ÷ÁֲŴó">¡¾Î¹Ê֪С¿Ê²Ã´Äñ¶¼ÓеÄÊ÷ÁֲŴó</a></li>
+ <li><a href="http://www.infzm.com/content/35669" title="¡¾Ð´Õæ¡¿Ôıø¡¤¼â¶ËÀûÆ÷¶á¿áÉ">¡¾Ð´Õæ¡¿Ôıø¡¤¼â¶ËÀûÆ÷¶á¿áÉ</a></li>
+ <li><a href="http://www.infzm.com/content/35673" title="½»¾¯ÍϳµÊÕ·Ñ£ºµØ·½Á¢·¨Óë¹ú¼ÒÁ¢·¨´òÆðÁ˼Ü">½»¾¯ÍϳµÊÕ·Ñ£ºµØ·½Á¢·¨Óë¹ú¼ÒÁ¢·¨´òÆðÁ˼Ü</a></li>
+ <li><a href="http://www.infzm.com/content/35674" title="Öйú¾üÊÂÁ¢·¨´óÌáËÙ">Öйú¾üÊÂÁ¢·¨´óÌáËÙ</a></li>
+ <li><a href="http://www.infzm.com/content/35675" title="¡°ÈÃÕŽ£°¸³ÉΪָµ¼ÐÔ°¸Àý¡±">¡°ÈÃÕŽ£°¸³ÉΪָµ¼ÐÔ°¸Àý¡±</a></li>
+
+ <li><a href="http://www.infzm.com/content/35676" title="ÈËÌåÊÔÑ飬Öйú·¨ÂÉÈçºÎÃæ¶Ô">ÈËÌåÊÔÑ飬Öйú·¨ÂÉÈçºÎÃæ¶Ô</a></li>
+ <li><a href="http://www.infzm.com/content/35677" title="±»²ðǨÕßͱËÀ²ðǨÕß ±»ÅлºÐÌÖØ»ñ×ÔÓÉ">±»²ðǨÕßͱËÀ²ðǨÕß ±»ÅлºÐÌÖØ»ñ×ÔÓÉ</a></li>
+ <li><a href="http://www.infzm.com/content/35678" title="ÓÐ´í¼´¸Ä£¨091008£©">ÓÐ´í¼´¸Ä£¨091008£©</a></li>
+ </ul>
+ </dd>
+ </dl>
+ </div>
+
+ <div class="right">
+ <h2>ʱ¾Ö</h2>
+ <dl>
+ <dt></dt>
+ <dd>
+ <ul class="relnews">
+ <li><a href="http://www.infzm.com/content/35670" title="¸®ÔºÐÂÎÅ£¨091008£©">¸®ÔºÐÂÎÅ£¨091008£©</a></li>
+ <li><a href="http://www.infzm.com/content/35671" title="ÎåÐǺìÆìÊÇÔõÑùÔÚ°×¹¬Ç°ÉýÆðµÄ£¿">ÎåÐǺìÆìÊÇÔõÑùÔÚ°×¹¬Ç°ÉýÆðµÄ£¿</a></li>
+
+ <li><a href="http://www.infzm.com/content/35672" title="ÃÀ¹úÒ½¸Ä¹Û²ì£ºËµÄ¸Ä¸ï£¿¸ÄË£¿">ÃÀ¹úÒ½¸Ä¹Û²ì£ºËµÄ¸Ä¸ï£¿¸ÄË£¿</a></li>
+ </ul>
+ </dd>
+ </dl>
+ <h2>ÂÌÉ«</h2>
+ <dl>
+ <dt></dt>
+ <dd>
+
+ <ul class="relnews">
+ <li><a href="http://www.infzm.com/content/35640" title="ÈÕ±¾Â̼ø">ÈÕ±¾Â̼ø</a></li>
+ <li><a href="http://www.infzm.com/content/35641" title="»·±£NGOµÄÖйúÉúÃüÊ·">»·±£NGOµÄÖйúÉúÃüÊ·</a></li>
+ <li><a href="http://www.infzm.com/content/35642" title="Å·ÖÞÎå¹úÍâ½»²¿³¤ÁªºÏÉùÃ÷">Å·ÖÞÎå¹úÍâ½»²¿³¤ÁªºÏÉùÃ÷</a></li>
+ <li><a href="http://www.infzm.com/content/35643" title="Éú̬Êé¼Ç">Éú̬Êé¼Ç</a></li>
+ <li><a href="http://www.infzm.com/content/35644" title="ÐÑÀ´£¬Ïò×ÅÂÌɫǰ½ø">ÐÑÀ´£¬Ïò×ÅÂÌɫǰ½ø</a></li>
+
+ <li><a href="http://www.infzm.com/content/35645" title="¡¾¿ª°æ´Ê¡¿ÎªÂ̶øÉú">¡¾¿ª°æ´Ê¡¿ÎªÂ̶øÉú</a></li>
+ </ul>
+ </dd>
+ </dl>
+ <h2>ÎÄ»¯</h2>
+ <dl>
+ <dt></dt>
+ <dd>
+
+ <ul class="relnews">
+ <li><a href="http://www.infzm.com/content/35681" title="ÁìÐäÍòËê¹ú¼ÒÍòË껹ÓÐÈËÃñÍòËê">ÁìÐäÍòËê¹ú¼ÒÍòË껹ÓÐÈËÃñÍòËê</a></li>
+ <li><a href="http://www.infzm.com/content/35682" title="¡°Ëü²»ÊÇÒ»¸öÍí»á¸ÅÄ¶øÊÇÒ»¸ö¹²Í¬»¶Àֵį·ÅÆ¡±¡ª¡ª×¨·Ã¹úÇì60ÖÜÄêÁª»¶Íí»áÖ´ÐÐ×ܵ¼Ñݼ׶¡">¡°Ëü²»ÊÇÒ»¸öÍí»á¸ÅÄ¶øÊÇÒ»¸ö¹²Í¬»¶Àֵį·ÅÆ¡±¡ª...</a></li>
+ <li><a href="http://www.infzm.com/content/35683" title="ÈËÓ붯ÎïµÄÖÇÁ¦ºè¹µ">ÈËÓ붯ÎïµÄÖÇÁ¦ºè¹µ</a></li>
+ <li><a href="http://www.infzm.com/content/35684" title="¸Ä¸ï¿ª·ÅµÚÒ»¶¨ÂÉ£º×ÔÓɶ¨ÂÉ¡ª¡ª¶ÁÌï¼ÍÔÆ¡¶¸Ä¸ï¿ª·ÅµÄΰ´óʵ¼ù¡·Ö®Ò»">¸Ä¸ï¿ª·ÅµÚÒ»¶¨ÂÉ£º×ÔÓɶ¨ÂÉ¡ª¡ª¶ÁÌï¼ÍÔÆ¡¶¸Ä¸ï¿ª·Å...</a></li>
+ <li><a href="http://www.infzm.com/content/35685" title="¸Ä¸ï¿ª·ÅµÚ¶þ¶¨ÂÉ£ºµÃµÀÕß¶àÖú¡ª¡ª¶ÁÌï¼ÍÔÆ¡¶¸Ä¸ï¿ª·ÅµÄΰ´óʵ¼ù¡·Ö®¶þ">¸Ä¸ï¿ª·ÅµÚ¶þ¶¨ÂÉ£ºµÃµÀÕß¶àÖú¡ª¡ª¶ÁÌï¼ÍÔÆ¡¶¸Ä¸ï¿ª...</a></li>
+
+ <li><a href="http://www.infzm.com/content/35686" title="¸Ä¸ï¿ª·ÅµÚÈý¶¨ÂÉ£ºÊշŶ¨ÂÉ¡ª¡ª¶ÁÌï¼ÍÔÆ¡¶¸Ä¸ï¿ª·ÅµÄΰ´óʵ¼ù¡·Ö®Èý">¸Ä¸ï¿ª·ÅµÚÈý¶¨ÂÉ£ºÊշŶ¨ÂÉ¡ª¡ª¶ÁÌï¼ÍÔÆ¡¶¸Ä¸ï¿ª·Å...</a></li>
+ <li><a href="http://www.infzm.com/content/35687" title="¡¶½â·ÅÕ½Õù¡·×÷ÕßÍõÊ÷Ôö£º¡°Ã»ÓÐʲô±Èµç±¨¸üÕæÊµµÄÁË¡±">¡¶½â·ÅÕ½Õù¡·×÷ÕßÍõÊ÷Ôö£º¡°Ã»ÓÐʲô±Èµç±¨¸üÕæÊµµÄ...</a></li>
+ <li><a href="http://www.infzm.com/content/35688" title="¶¼Ëµ×Ô¼ºÃ»Ðé¹¹µçÊӾ硶½â·Å¡·±à¾çÍõ³¯Öù£º¡°ÕâÑùµÄÇé½ÚÎÒÄĸұడ£¿¡±">¶¼Ëµ×Ô¼ºÃ»Ðé¹¹µçÊӾ硶½â·Å¡·±à¾çÍõ³¯Öù£º¡°ÕâÑùµÄ...</a></li>
+ <li><a href="http://www.infzm.com/content/35689" title="²Ì¹úÇ¿£ºÕâÊÇÃÀÀöµÄ׿¹ú£¬¾Í¹»ÁË">²Ì¹úÇ¿£ºÕâÊÇÃÀÀöµÄ׿¹ú£¬¾Í¹»ÁË</a></li>
+ </ul>
+ </dd>
+ </dl>
+
+ </div>
+
+ </div><!--end .side-1-->
+ </div><!--end .inner .col-2lb-->
+</div><!--end #body-->
+ <!--CONTENT END-->
+ <div class="clear"></div>
+ </div>
+ <div class="clear"></div>
+ <!--µ×²¿-->
+
+ <div id="footer">
+ <h3><a id="backTop" href="#">·µ»Ø¶¥²¿</a>ÄÏ·½ÖÜÄ©¹Ù·½ÍøÕ¾----www.infzm.com</h3>
+ <div id="footerNav" class="inner">
+ <div class="side-1">
+ <dl class="navList">
+ <dt><span class="a">·þÎñ</span></dt>
+ <dd><a href="http://group.infzm.com">ÄÏÖÜ´óÔº</a></dd>
+
+ <dd><a href="http://www.infzm.com/z.shtml">רÀ¸</a></dd>
+ <dd><a href="http://bbs.infzm.com">ÂÛ̳</a></dd>
+ <dd><a href="http://bbs.infzm.com/forumdisplay.php?fid=38">ÉÌÆ·</a></dd>
+ <dd class="noBor"><a href="">µç×Ó±¨¿¯</a></dd>
+ </dl>
+ <dl class="navList">
+ <dt><span class="b">×ÊѶ</span></dt>
+
+ <dd><a href="http://www.infzm.com/news.shtml">ÐÂÎÅ</a></dd>
+ <dd><a href="http://www.infzm.com/economy.shtml">¾¼Ã</a></dd>
+ <dd><a href="http://www.infzm.com/culture.shtml">ÎÄ»¯</a></dd>
+ <dd><a href="http://www.infzm.com/review.shtml">ÆÀÂÛ</a></dd>
+ <dd><a href="http://www.infzm.com/picture.shtml">ͼƬ</a></dd>
+ <dd class="noBor"><a href="http://www.infzm.com/fashion.shtml">Éú»î</a></dd>
+
+ </dl>
+ <dl class="navList red">
+ <dd class="first"><a href="http://www.infzm.com/rss/home/rss2.0.xml">RSS¶©ÔÄ</a></dd>
+ <dd><a href="">ÊÖ»ú±¨</a></dd>
+ <dd class="noBor"><a href="">¹ã¸æ</a></dd>
+ </dl>
+ </div>
+
+ <div class="side-2">
+ <dl class="navList">
+ <dt><span class="c"><a href="http://www.infzm.com/aboutus" target="_blank">¹ØÓÚÎÒÃÇ</a></span></dt>
+ <dd><a href="http://www.infzm.com/">infzm.com</a></dd>
+ <dd><a href="http://www.infzm.com/content/24164" target="_blank">ÄÏ·½ÖÜÄ©</a></dd>
+ <dd><a href="http://mangazine.infzm.com/" target="_blank">ÃûÅÆÔÓÖ¾</a></dd>
+ <dd class="noBor"><a href="http://www.infzm.com/nfrwzk/" target="_blank">ÄÏ·½ÈËÎïÖÜ¿¯</a></dd>
+
+ </dl>
+ <dl class="navList">
+ <dt><span class="d"><a href="http://www.infzm.com/event/">Æ·ÅÆ»î¶¯</a></span></dt>
+ <dd><a href="http://csr.infzm.com">ÄÏÖܹ«Òæ</a></dd>
+ <dd><a href="http://www.infzm.com/rich/">´´¸»¡¤500Ç¿</a></dd>
+ <dd class="noBor"><a href="http://www.infzm.com/topic/partnership.shtml">ºÏ×÷»ï°é</a></dd>
+ </dl>
+
+ <dl class="navList blue">
+ <dd class="first"><a href="http://www.infzm.com/topic/jobs.shtml" target="_blank">¼ÓÈëÎÒÃÇ</a></dd>
+ <dd class="first"><a href="http://z.infzm.com" target="_blank">¹Ù·½²©¿Í</a></dd>
+ <dd class="first"><a href="">Õ¾µãµØÍ¼</a></dd>
+ <dd><a href="http://www.infzm.com/aboutus/200803/t20080317_40300.htm" target="_blank">Óû§ÊØÔò</a></dd>
+ <dd class="noBor"><a href="">°æÈ¨ÉùÃ÷</a></dd>
+
+ </dl>
+ </div>
+ <div class="clear"></div>
+ </div>
+ <div class="inner Otherinfo">
+ <dl>
+ <dt>ÄÏ·½±¨Òµ´«Ã½¼¯ÍÅÖ÷°ì:</dt>
+ <dd><a href="http://www.nfdaily.cn/" target="_blank">ÄÏ·½ÈÕ±¨</a></dd>
+
+ <dd><a href="http://www.nanfangdaily.com.cn/southnews/dd/nc/" target="_blank">ÄÏ·½Å©´å±¨</a></dd>
+ <dd><a href="http://www.infzm.com">ÄÏ·½ÖÜÄ©</a></dd>
+ <dd><a href="http://www.nddaily.com/" target="_blank">ÄÏ·½¶¼Êб¨</a></dd>
+ <dd><a href="http://www.21cbh.com/" target="_blank">21ÊÀ¼Í¾¼Ã±¨µÀ</a></dd>
+ <dd><a href="http://www.thebeijingnews.com/" target="_blank">о©±¨</a></dd>
+ <dd><a href="http://www.xjrb.net" target="_blank">Î÷½ÈÕ±¨</a></dd>
+
+ <dd><a href="http://www.ynxxb.com/" target="_blank">ÔÆÄÏÐÅÏ¢±¨</a></dd>
+ <dd><a href="http://www.nbweekly.com/" target="_blank">Ä϶¼ÖÜ¿¯</a></dd>
+ <dd><a href="http://www.fengshangweekly.com/" target="_blank">·çÉÐÖܱ¨</a></dd>
+ <dd><a href="http://moneyweek.dooland.com/" target="_blank">Àí²ÆÖܱ¨</a></dd>
+ <dd><a href="http://www.nfyk.com/" target="_blank">ÄÏ·½</a></dd>
+ <dd class="secondline"><a href="http://www.nanfangdaily.com.cn/hb/20090428/" target="_blank">³ÇÊл±¨</a></dd>
+ <dd><a href="http://mangazine.infzm.com/" target="_blank">ÃûÅÆ</a></dd>
+
+ <dd><a href="http://www.infzm.com/nfrwzk/" target="_blank">ÄÏ·½ÈËÎïÖÜ¿¯</a></dd>
+ <dd><a href="http://www.21cbr.com/" target="_blank">21ÊÀ¼ÍÉÌÒµÆÀÂÛ</a></dd>
+ <dd><a href="" target="_blank">ÉÌÎñÂÃÐÐ</a></dd>
+ <dd><a href="http://www.southcn.com/" target="_blank">ÄÏ·½Íø</a></dd>
+ <dd><a href="http://www.nanfangdaily.com.cn/" target="_blank">ÄÏ·½±¨ÒµÍø</a></dd>
+ </dl>
+
+ <p><a href="http://www.southcn.com/">¹ã¶«ÄÏ·½ÍøÂçÐÅÏ¢¿Æ¼¼ÓÐÏÞ¹«Ë¾</a>¸ºÔðÖÆ×÷ά»¤ | ÐÂÎÅÐÅÏ¢·þÎñÐí¿ÉÖ¤ ICP¾ÓªÐí¿ÉÖ¤ºÅ£ºÔÁB2-20050235ºÅ</p>
+ </div>
+<div id="analytic">
+ <!--by google analytic-->
+ <script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
+ </script>
+ <script type="text/javascript">
+ _uacct = "UA-2915863-1";
+ urchinTracker();
+ </script>
+</div> </div><!--end #footer-->
+
+</div>
+</body>
+</html>
+</body>
+</html>
diff --git a/lib/nanzhou.rb b/lib/nanzhou.rb
index 20f4864..084c46c 100644
--- a/lib/nanzhou.rb
+++ b/lib/nanzhou.rb
@@ -1,34 +1,160 @@
+#!/usr/bin/ruby
+require 'singleton'
require 'cgi'
require 'rubygems'
require 'patron'
require 'hpricot'
-class NanzhouCrawler
+require 'extensions/all'
+
+module ParseModule
+ attr_reader :doc
+ def do_request(path)
+ @doc = new_request(path)
+ end
+
+ def new_request(path)
+ puts "Request #{path}"
+ Nanzhou.instance.get_doc(path)
+ end
+
+ def at(path)
+ doc.at(path)
+ end
+
+ def at_html(path)
+ at(path).inner_html
+ end
+
+ def at_text(path)
+ at(path).inner_text
+ end
+
+ def search(path)
+ doc.search(path)
+ end
+
+ def at_url_pair(path)
+ a = at(path)
+ [a['href'], a.inner_html]
+ end
+end
+
+class Journal
+ URL_BASE = 'enews/infzm/'
+ PART = {'ç»æµ'=>0, 'è¯è®º'=>1, 'æ°é»'=>2, 'æ¶å±'=>3, '绿è²' =>4 , 'æå'=>5}
+ include ParseModule
+ attr_accessor :id, :name, :headline, :parted_content
+
+ def initialize(url, name)
+ url.chomp("/") =~/(\d+)$/
+ @id = $1.to_i
+ raise "id #{$1} is not valid" if @id <= 0
+ @name = name
+ end
+
+ def parse!
+ do_request(URL_BASE+self.id.to_s)
+ self.headline = create_content(at(".topnews a"), :head, 0,at_text(".topnews .summary"))
+ raise if headline.nil?
+ self.parted_content = search(".side-2 h2").map{|e|parse_parts(e, PART[e.inner_text])}
+ end
+
+ def parse_parts(element, part)
+ next_node = element.next
+ while next_node&&(next_node = next_node.next).text?
+ puts "ingore text"
+ end
+ next_node.search(".relnews li a").map_with_index do |a, i|
+ create_content(a, part , i)
+ end
+
+ end
+
+
+ private
+ def create_content(href_element, part, position_of_part, subtitle=nil)
+ url, title = href_element['href'], href_element.inner_text
+ url =~/(\d+)$/
+
+ Content.from_hash(:journal=>self, :id => $1,
+ :part=>part, :position_of_part=>position_of_part,
+ :title => title, :title2=> subtitle )
+ end
+end
+
+class Content < Struct.new(:journal, :id, :part, :title, :position_of_part, :title2)
+ URL_BASE = 'content/'
+ include ParseModule
+ attr_reader :pages, :author, :publish_at
+ def self.from_hash(hash)
+ result = self.new
+ hash.each{|k,v|result[k]=v}
+ result
+ end
+ def parse!
+ do_request(URL_BASE+self.id.to_s)
+ @author = at_text(".relInfo span.author strong")
+ @publish_at = DateTime.parse(at_text(".relInfo span.pubTime"))
+ @pages = [at_html("#content-context")]
+ pages = search("#pageNum .pages a")
+ if(pages&&pages.pop)
+ pages.each{|e|
+ e['href'] =~ /\/(\d+)$/
+ @pages<< crawl_page($1)
+ }
+ end
+ end
+
+ def crawl_page(page_num)
+ doc = new_request(URL_BASE+self.id.to_s+"/#{page_num}")
+ doc.at("#content-context").inner_html
+ end
+end
+
+class Nanzhou
+ include Singleton
def initialize
@session_config = {"Content-Type"=>'application/x-www-form-urlencoded',
+ "Accept" => "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"User-Agent" => "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2",
"Referer" => "http://www.infzm.com/enews/infzm",
- "Cookie" => %[d041ab46875f9b703c33b8d4c126c757=+4+F+15F1E585E+7+D46+B+E5B1B56+44C405D+759445E5F5B535F4659+05C16145C52+A+95846+C4B; PHPSESSID=j9kh4tgje6lrbeg47bavdl82q6; __utmc=118487249; __utmz=118487249.1255250270.2.2.utmccn=(organic)|utmcsr=google|utmctr=%E5%8D%97%E6%96%B9%E5%91%A8%E6%9C%AB|utmcmd=organic; __utma=118487249.1960636661.1255245331.1255245331.1255250270.2; OAID=25e4cf710198ddf0d10943a88a72b4b4; __utmb=118487249]
-
+ # "Accept-Encoding" => "gzip,deflate",
+ "Accept-Charset" => "ISO-8859-1,utf-8;q=0.7,*;q=0.7",
+ "Accept-Language" => "en-us,en;q=0.5",
+ "Cookie" => %[PHPSESSID=t7ot0hth64p8q0i0sdaallps07; __utma=118487249.973348149.1255276544.1255276544.1255276544.1; __utmb=118487249; __utmc=118487249; __utmz=118487249.1255276544.1.1.utmccn=(organic)|utmcsr=google|utmctr=%E5%8D%97%E6%96%B9%E5%91%A8%E6%9C%AB|utmcmd=organic; OAID=0704d0594d5c9420942f7bb16db28e1f; d041ab46875f9b703c33b8d4c126c757=55+350+3425F+D565E15+A+0+21055504D415E+6+7165A+D+B+2+A46+3+258154550+356555F155D18]
+
}
@base_url = 'http://www.infzm.com/'
end
- def parse
- doc = Hpricot(session.get("content/35661").body)
+ def get_doc(path)
+ doc = Hpricot(session.get(path).body)
+ end
+
+ def parse_journals
+ content = File.read(File.dirname(__FILE__)+"/index.html.data")
+ result = Hpricot(content).search("select option").map do |option|
+ Journal.new(option['value'], option.inner_html)
+ end
+ result
end
- private
def session
unless @session
sess = Patron::Session.new
sess.handle_cookies
sess.base_url = @base_url
@session_config.each do |k,v|
sess.headers[k] = v
end
@session = sess
end
@session
end
-
+end
+if $0 == __FILE__
+ js = Nanzhou.instance.parse_journals
+ j = js.first
+ j.parse!
+ j.headline.parse!
end
\ No newline at end of file
|
dazuiba/fansof
|
fba9103ec2d2d4e04058952349ce833583d0fba6
|
data files
|
diff --git a/db/development.sqlite3 b/db/development.sqlite3
new file mode 100644
index 0000000..9d95d78
Binary files /dev/null and b/db/development.sqlite3 differ
|
dazuiba/fansof
|
374efd1d8a3d5eaa9e367083f456f6746de5b51e
|
remove community_engine
|
diff --git a/.eprj b/.eprj
index a2d30b7..db31bf4 100755
--- a/.eprj
+++ b/.eprj
@@ -1,11 +1,28 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
+ <key>filters</key>
+ <dict>
+ <key>excludeDirs</key>
+ <array>
+ <string>.*</string>
+ </array>
+ <key>excludeFiles</key>
+ <array />
+ <key>includeDirs</key>
+ <array />
+ <key>includeFiles</key>
+ <array />
+ </dict>
<key>fileTriggers</key>
<dict>
<key>env</key>
<string>config\environment.rb</string>
+ <key>flash_session_cookie_middleware.rb</key>
+ <string>vendor\plugins\community_engine\lib\flash_session_cookie_middleware.rb</string>
+ <key>route</key>
+ <string>config\routes.rb</string>
</dict>
</dict>
</plist>
diff --git a/README b/README
deleted file mode 100755
index 37ec8ea..0000000
--- a/README
+++ /dev/null
@@ -1,243 +0,0 @@
-== Welcome to Rails
-
-Rails is a web-application framework that includes everything needed to create
-database-backed web applications according to the Model-View-Control pattern.
-
-This pattern splits the view (also called the presentation) into "dumb" templates
-that are primarily responsible for inserting pre-built data in between HTML tags.
-The model contains the "smart" domain objects (such as Account, Product, Person,
-Post) that holds all the business logic and knows how to persist themselves to
-a database. The controller handles the incoming requests (such as Save New Account,
-Update Product, Show Post) by manipulating the model and directing data to the view.
-
-In Rails, the model is handled by what's called an object-relational mapping
-layer entitled Active Record. This layer allows you to present the data from
-database rows as objects and embellish these data objects with business logic
-methods. You can read more about Active Record in
-link:files/vendor/rails/activerecord/README.html.
-
-The controller and view are handled by the Action Pack, which handles both
-layers by its two parts: Action View and Action Controller. These two layers
-are bundled in a single package due to their heavy interdependence. This is
-unlike the relationship between the Active Record and Action Pack that is much
-more separate. Each of these packages can be used independently outside of
-Rails. You can read more about Action Pack in
-link:files/vendor/rails/actionpack/README.html.
-
-
-== Getting Started
-
-1. At the command prompt, start a new Rails application using the <tt>rails</tt> command
- and your application name. Ex: rails myapp
-2. Change directory into myapp and start the web server: <tt>script/server</tt> (run with --help for options)
-3. Go to http://localhost:3000/ and get "Welcome aboard: You're riding the Rails!"
-4. Follow the guidelines to start developing your application
-
-
-== Web Servers
-
-By default, Rails will try to use Mongrel if it's are installed when started with script/server, otherwise Rails will use WEBrick, the webserver that ships with Ruby. But you can also use Rails
-with a variety of other web servers.
-
-Mongrel is a Ruby-based webserver with a C component (which requires compilation) that is
-suitable for development and deployment of Rails applications. If you have Ruby Gems installed,
-getting up and running with mongrel is as easy as: <tt>gem install mongrel</tt>.
-More info at: http://mongrel.rubyforge.org
-
-Say other Ruby web servers like Thin and Ebb or regular web servers like Apache or LiteSpeed or
-Lighttpd or IIS. The Ruby web servers are run through Rack and the latter can either be setup to use
-FCGI or proxy to a pack of Mongrels/Thin/Ebb servers.
-
-== Apache .htaccess example for FCGI/CGI
-
-# General Apache options
-AddHandler fastcgi-script .fcgi
-AddHandler cgi-script .cgi
-Options +FollowSymLinks +ExecCGI
-
-# If you don't want Rails to look in certain directories,
-# use the following rewrite rules so that Apache won't rewrite certain requests
-#
-# Example:
-# RewriteCond %{REQUEST_URI} ^/notrails.*
-# RewriteRule .* - [L]
-
-# Redirect all requests not available on the filesystem to Rails
-# By default the cgi dispatcher is used which is very slow
-#
-# For better performance replace the dispatcher with the fastcgi one
-#
-# Example:
-# RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]
-RewriteEngine On
-
-# If your Rails application is accessed via an Alias directive,
-# then you MUST also set the RewriteBase in this htaccess file.
-#
-# Example:
-# Alias /myrailsapp /path/to/myrailsapp/public
-# RewriteBase /myrailsapp
-
-RewriteRule ^$ index.html [QSA]
-RewriteRule ^([^.]+)$ $1.html [QSA]
-RewriteCond %{REQUEST_FILENAME} !-f
-RewriteRule ^(.*)$ dispatch.cgi [QSA,L]
-
-# In case Rails experiences terminal errors
-# Instead of displaying this message you can supply a file here which will be rendered instead
-#
-# Example:
-# ErrorDocument 500 /500.html
-
-ErrorDocument 500 "<h2>Application error</h2>Rails application failed to start properly"
-
-
-== Debugging Rails
-
-Sometimes your application goes wrong. Fortunately there are a lot of tools that
-will help you debug it and get it back on the rails.
-
-First area to check is the application log files. Have "tail -f" commands running
-on the server.log and development.log. Rails will automatically display debugging
-and runtime information to these files. Debugging info will also be shown in the
-browser on requests from 127.0.0.1.
-
-You can also log your own messages directly into the log file from your code using
-the Ruby logger class from inside your controllers. Example:
-
- class WeblogController < ActionController::Base
- def destroy
- @weblog = Weblog.find(params[:id])
- @weblog.destroy
- logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!")
- end
- end
-
-The result will be a message in your log file along the lines of:
-
- Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1
-
-More information on how to use the logger is at http://www.ruby-doc.org/core/
-
-Also, Ruby documentation can be found at http://www.ruby-lang.org/ including:
-
-* The Learning Ruby (Pickaxe) Book: http://www.ruby-doc.org/docs/ProgrammingRuby/
-* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide)
-
-These two online (and free) books will bring you up to speed on the Ruby language
-and also on programming in general.
-
-
-== Debugger
-
-Debugger support is available through the debugger command when you start your Mongrel or
-Webrick server with --debugger. This means that you can break out of execution at any point
-in the code, investigate and change the model, AND then resume execution!
-You need to install ruby-debug to run the server in debugging mode. With gems, use 'gem install ruby-debug'
-Example:
-
- class WeblogController < ActionController::Base
- def index
- @posts = Post.find(:all)
- debugger
- end
- end
-
-So the controller will accept the action, run the first line, then present you
-with a IRB prompt in the server window. Here you can do things like:
-
- >> @posts.inspect
- => "[#<Post:0x14a6be8 @attributes={\"title\"=>nil, \"body\"=>nil, \"id\"=>\"1\"}>,
- #<Post:0x14a6620 @attributes={\"title\"=>\"Rails you know!\", \"body\"=>\"Only ten..\", \"id\"=>\"2\"}>]"
- >> @posts.first.title = "hello from a debugger"
- => "hello from a debugger"
-
-...and even better is that you can examine how your runtime objects actually work:
-
- >> f = @posts.first
- => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>
- >> f.
- Display all 152 possibilities? (y or n)
-
-Finally, when you're ready to resume execution, you enter "cont"
-
-
-== Console
-
-You can interact with the domain model by starting the console through <tt>script/console</tt>.
-Here you'll have all parts of the application configured, just like it is when the
-application is running. You can inspect domain models, change values, and save to the
-database. Starting the script without arguments will launch it in the development environment.
-Passing an argument will specify a different environment, like <tt>script/console production</tt>.
-
-To reload your controllers and models after launching the console run <tt>reload!</tt>
-
-== dbconsole
-
-You can go to the command line of your database directly through <tt>script/dbconsole</tt>.
-You would be connected to the database with the credentials defined in database.yml.
-Starting the script without arguments will connect you to the development database. Passing an
-argument will connect you to a different database, like <tt>script/dbconsole production</tt>.
-Currently works for mysql, postgresql and sqlite.
-
-== Description of Contents
-
-app
- Holds all the code that's specific to this particular application.
-
-app/controllers
- Holds controllers that should be named like weblogs_controller.rb for
- automated URL mapping. All controllers should descend from ApplicationController
- which itself descends from ActionController::Base.
-
-app/models
- Holds models that should be named like post.rb.
- Most models will descend from ActiveRecord::Base.
-
-app/views
- Holds the template files for the view that should be named like
- weblogs/index.html.erb for the WeblogsController#index action. All views use eRuby
- syntax.
-
-app/views/layouts
- Holds the template files for layouts to be used with views. This models the common
- header/footer method of wrapping views. In your views, define a layout using the
- <tt>layout :default</tt> and create a file named default.html.erb. Inside default.html.erb,
- call <% yield %> to render the view using this layout.
-
-app/helpers
- Holds view helpers that should be named like weblogs_helper.rb. These are generated
- for you automatically when using script/generate for controllers. Helpers can be used to
- wrap functionality for your views into methods.
-
-config
- Configuration files for the Rails environment, the routing map, the database, and other dependencies.
-
-db
- Contains the database schema in schema.rb. db/migrate contains all
- the sequence of Migrations for your schema.
-
-doc
- This directory is where your application documentation will be stored when generated
- using <tt>rake doc:app</tt>
-
-lib
- Application specific libraries. Basically, any kind of custom code that doesn't
- belong under controllers, models, or helpers. This directory is in the load path.
-
-public
- The directory available for the web server. Contains subdirectories for images, stylesheets,
- and javascripts. Also contains the dispatchers and the default HTML files. This should be
- set as the DOCUMENT_ROOT of your web server.
-
-script
- Helper scripts for automation and generation.
-
-test
- Unit and functional tests along with fixtures. When using the script/generate scripts, template
- test files will be generated for you and placed in this directory.
-
-vendor
- External libraries that the application depends on. Also includes the plugins subdirectory.
- If the app has frozen rails, those gems also go here, under vendor/rails/.
- This directory is in the load path.
diff --git a/vendor/plugins/community_engine/init.rb b/vendor/plugins/community_engine/init.rb.bak
old mode 100755
new mode 100644
similarity index 100%
rename from vendor/plugins/community_engine/init.rb
rename to vendor/plugins/community_engine/init.rb.bak
|
eric1234/file_browser
|
a4c13e4dfba4c781902e90b355f284269bceecd2
|
Switch to jQuery
|
diff --git a/README.rdoc b/README.rdoc
index e867801..c25a499 100644
--- a/README.rdoc
+++ b/README.rdoc
@@ -1,61 +1,68 @@
= DESCRIPTION
A rails plugin that provides a basic file browser. The primary use
case for this plugin is:
* To manage a directory of files includes subdirectories
* To integration with products like CKEditor for selecting files.
Guiding Principals:
* No database required
* Pluggable backends (filesystem, S3, etc.) - Filesystem only currently
* Pluggable integration with 3rd party products such as CKEditor
Possible Future Features:
* Launcher can specify only certain file types to show
(images only, only certain extensions, etc.)
* Allow basic image manipulation (resize, crop, etc.)
* File upload progress monitoring (for large files)
-* Icon previews (mainly for images show thumbnail for icon)
= SETUP
-In your Gemfile add:
+First, your app needs to be using jQuery as it's JavaScript framework.
+This dependency might be removed at some future point but it is
+required for now. In your Gemfile add:
gem 'file_browser'
In an initializer add:
FileBrowser.storages[:local] =
FilesystemStorage.new Rails.root.join('public/uploaded_files')
Change the above path to be wherever you want to write files. Also make
sure that directory is writable by the application.
-Copy the assets to your public directory. This will likely later be
-automated as Rails adds support.
-
Finally point your browser to /local/uploaded_files/index and start
managing your files via the web.
-See example_integrations directory for how to integrate with 3rd party
-tools such as CKEditor.
+= CKEditor Integration
+
+CKEditor integration is provided out of the box. When configuring
+CKEditor make sure to provide the following attributes:
+
+ filebrowserBrowseUrl: '/local/uploaded_files/select/ck_browser',
+ filebrowserUploadUrl: '/local/uploaded_files/drop/ck_browser',
+
+This assumes your storage is named "local", if you name it something
+else then change the above configuration. Then add "ck_browser" to
+your asset pipeline.
= CONFIGURATION
By default the app will use the "file_browser" layout. Obviously your
can override that in your application if you want. If you want it to
use the same layout as your main layout simply symlink
file_browser.html.erb to your application.html.erb file. If you use
-your own layout make sure that it includes the prototype library and
+your own layout make sure that it includes the jQuery library and
that it yields to the symbol :file_browser_footer.
You can have multiple storage repositories that can be registered and
accessed. See FileBrowser#storages for more info.
= CREDIT
This gem was developed by Eric Anderson (http://pixelwareinc.com) while
developing projects under Red Tusk Studios (http://redtusk.com).
diff --git a/app/assets/javascripts/ck_browser.js.coffee b/app/assets/javascripts/ck_browser.js.coffee
new file mode 100644
index 0000000..c45704d
--- /dev/null
+++ b/app/assets/javascripts/ck_browser.js.coffee
@@ -0,0 +1,6 @@
+# CKEditor integration
+jQuery(document).ready ($)->
+ $(document).on 'file_browser:select', (event, url)->
+ func = window.location.search.match(/CKEditorFuncNum=([^&]+)/)[1]
+ (window.opener || window.parent).CKEDITOR.tools.callFunction func, url
+ window.close()
diff --git a/app/assets/javascripts/file_browser.js b/app/assets/javascripts/file_browser.js
deleted file mode 100644
index b770a7d..0000000
--- a/app/assets/javascripts/file_browser.js
+++ /dev/null
@@ -1,13 +0,0 @@
-Event.observe(document, 'dom:loaded', function() {
-
- var items = $$('#directory-index.clickable li.file');
- items.each(function(e) {
- e.observe('click', function() {
- if(event.element().getAttribute('value') == 'X') return;
- event.stop();
- var target = event.element().up('li').down('a');
- document.fire('file_browser:select', target.getAttribute('href'));
- })
- });
-
-});
diff --git a/app/assets/javascripts/file_browser.js.coffee b/app/assets/javascripts/file_browser.js.coffee
new file mode 100644
index 0000000..34344e2
--- /dev/null
+++ b/app/assets/javascripts/file_browser.js.coffee
@@ -0,0 +1,9 @@
+//= require 'jquery'
+
+jQuery(document).ready ($)->
+ items = $ '#directory-index.clickable li.file'
+ items.click (event)->
+ return if $(event.target).attr('value') == 'X'
+ event.preventDefault();
+ target = $(this).find 'a'
+ target.trigger 'file_browser:select', target.attr('href')
diff --git a/app/views/layouts/file_browser.html.erb b/app/views/layouts/file_browser.html.erb
index fa88e9e..a1bec37 100644
--- a/app/views/layouts/file_browser.html.erb
+++ b/app/views/layouts/file_browser.html.erb
@@ -1,14 +1,14 @@
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>File Browser</title>
<%= stylesheet_link_tag 'file_browser', :media => :all %>
</head>
<body>
<%= yield %>
- <%= javascript_include_tag 'http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js', 'file_browser' %>
+ <%= javascript_include_tag 'file_browser' %>
<%= yield :file_browser_footer %>
</body>
-</html>
\ No newline at end of file
+</html>
diff --git a/app/views/uploaded_files/create.html.erb b/app/views/uploaded_files/create.html.erb
index 07414f0..db38ef1 100644
--- a/app/views/uploaded_files/create.html.erb
+++ b/app/views/uploaded_files/create.html.erb
@@ -1,8 +1,9 @@
<% content_for :file_browser_footer do %>
<%= javascript_include_tag params[:integration] %>
- <%= javascript_tag %Q{
- Event.observe(document, 'dom:loaded', function() {
- document.fire('file_browser:select', '#{path_to_uploaded_file @uploaded_file}');
+ <%= javascript_tag %Q!
+ jQuery(document).ready(function($) {
+ $(document).trigger('file_browser:select',
+ '#{path_to_uploaded_file @uploaded_file}');
});
- } %>
+ ! %>
<% end %>
diff --git a/config/routes.rb b/config/routes.rb
index 7b7d814..8910445 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,29 +1,29 @@
Rails.application.routes.draw do
# For image preview and resize on serve
if defined? Dragonfly
- app = Dragonfly[:file_browser].configure_with :imagemagick
- endpoint = app.endpoint do |params, app|
+ Dragonfly.logger = Rails.logger
+ endpoint = Dragonfly.app.endpoint do |params, app|
storage = FileBrowser.storages[params[:storage].to_sym]
file = storage[Pathname.new params[:path]]
app.fetch_file(file.stream.path).thumb params[:size]
end
get ':storage/uploaded_files/resized/:size/(*path)' => endpoint,
:as => :resized_uploaded_file, :format => false
end
controller :uploaded_files do
get ':storage/uploaded_files/select/:integration/(*path)' => :index,
:as => 'select_uploaded_file', :format => false
get ':storage/uploaded_files/index/(*path)' => :index,
:as => 'uploaded_files', :format => false
get ':storage/uploaded_files/(*path)' => :show,
:as => 'uploaded_file', :format => false
post ':storage/uploaded_files/drop/:integration' => :create,
:defaults => {:dropbox => true}, :as => 'drop_uploaded_file'
post ':storage/uploaded_files/(*path)' => :create,
:as => 'create_uploaded_file', :format => false
delete ':storage/uploaded_files/(*path)' => :destroy,
:as => 'delete_uploaded_file', :format => false
end
end
diff --git a/example_integrations/ck_browser.js b/example_integrations/ck_browser.js
deleted file mode 100644
index 9fd15dc..0000000
--- a/example_integrations/ck_browser.js
+++ /dev/null
@@ -1,17 +0,0 @@
-/* Put this in your javascripts directory. Then configure CKEditor with
- * the following attributes:
- *
- * filebrowserBrowseUrl: '/local/uploaded_files/select/ck_browser',
- * filebrowserUploadUrl: '/local/uploaded_files/drop/ck_browser',
- *
- * (This assumes your storage is named "local")
- */
-Event.observe(document, 'dom:loaded', function() {
-
- Event.observe(document, 'file_browser:select', function(event) {
- params = window.location.search.toQueryParams();
- (window.opener || window.parent).CKEDITOR.tools.callFunction(params['CKEditorFuncNum'], event.memo);
- window.close();
- });
-
-});
diff --git a/file_browser.gemspec b/file_browser.gemspec
index 0d621c2..43b37e9 100644
--- a/file_browser.gemspec
+++ b/file_browser.gemspec
@@ -1,20 +1,20 @@
Gem::Specification.new do |s|
s.name = 'file_browser'
- s.version = '0.2.0'
+ s.version = '0.3.0'
s.homepage = 'http://wiki.github.com/eric1234/file_browser/'
s.author = 'Eric Anderson'
s.email = 'eric@pixelwareinc.com'
- s.add_dependency 'rails', '>= 4.0.0.rc1'
+ s.add_dependency 'rails', '>= 4.0.0'
s.files = Dir['**/*'].reject do |f|
f =~ /^test/ || f == 'file_browser.gemspec' || f =~ /^pkg/
end
s.has_rdoc = true
s.extra_rdoc_files << 'README.rdoc'
s.rdoc_options << '--main' << 'README.rdoc'
s.summary = 'A Rails-gem for managing files'
s.description = <<-DESCRIPTION
Provides a web-based UI to manage a filesystem. Useful as an
alternative to FTP and also to integrate with products such
as CKEditor.
DESCRIPTION
end
|
eric1234/file_browser
|
48767d9d328966f70625069d106ef2d1bba13c9f
|
Use preferred (and working) method of changing the precompiled assets.
|
diff --git a/file_browser.gemspec b/file_browser.gemspec
index 5a6e480..3426dd2 100644
--- a/file_browser.gemspec
+++ b/file_browser.gemspec
@@ -1,20 +1,20 @@
Gem::Specification.new do |s|
s.name = 'file_browser'
- s.version = '0.1.5'
+ s.version = '0.2.0'
s.homepage = 'http://wiki.github.com/eric1234/file_browser/'
s.author = 'Eric Anderson'
s.email = 'eric@pixelwareinc.com'
s.add_dependency 'rails', '> 3.1'
s.files = Dir['**/*'].reject do |f|
f =~ /^test/ || f == 'file_browser.gemspec' || f =~ /^pkg/
end
s.has_rdoc = true
s.extra_rdoc_files << 'README.rdoc'
s.rdoc_options << '--main' << 'README.rdoc'
s.summary = 'A Rails-gem for managing files'
s.description = <<-DESCRIPTION
Provides a web-based UI to manage a filesystem. Useful as an
alternative to FTP and also to integrate with products such
as CKEditor.
DESCRIPTION
end
diff --git a/lib/file_browser.rb b/lib/file_browser.rb
index b3d565b..aceed5d 100644
--- a/lib/file_browser.rb
+++ b/lib/file_browser.rb
@@ -1,34 +1,32 @@
module FileBrowser
# Stores all configured storages for the current app. The application
# should configure this similar to:
#
# FileBrowser.storages[:local] = FilesystemStorage.new('/path/to/root')
#
# When the browser is loaded it will have the key as the prefix. So
# for example:
#
# /local/uploaded_files
#
# Will pull the UploadedFilesController::index action using the :local
# key set above.
mattr_accessor :storages
self.storages = {}
# If set to true then the file browser provides no way to create
# directories or add files. So you can only select files. You can
# still add files via the drop functionality. This is not a security
# issue but just simplifying the interface so the file browser is
# as simple as possible.
mattr_accessor :select_only
self.select_only = false
mattr_accessor :resize
class Engine < Rails::Engine
- initializer "file_browser.configure.assets" do |app|
- app.config.assets.precompile += %w(file_browser.js file_browser.css)
- end
+ config.assets.precompile += %w(file_browser.js file_browser.css)
end
end
|
eric1234/file_browser
|
8908d50cb4568ebbbf6a0e4d3fe708fb0cc15100
|
Bump version
|
diff --git a/Gemfile.lock b/Gemfile.lock
index 7d2bd77..82dab44 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -1,92 +1,91 @@
PATH
remote: .
specs:
- file_browser (0.1.4)
+ file_browser (0.1.5)
rails (> 3.1)
GEM
remote: http://rubygems.org/
specs:
- actionmailer (3.2.9)
- actionpack (= 3.2.9)
- mail (~> 2.4.4)
- actionpack (3.2.9)
- activemodel (= 3.2.9)
- activesupport (= 3.2.9)
+ actionmailer (3.2.13)
+ actionpack (= 3.2.13)
+ mail (~> 2.5.3)
+ actionpack (3.2.13)
+ activemodel (= 3.2.13)
+ activesupport (= 3.2.13)
builder (~> 3.0.0)
erubis (~> 2.7.0)
journey (~> 1.0.4)
- rack (~> 1.4.0)
+ rack (~> 1.4.5)
rack-cache (~> 1.2)
rack-test (~> 0.6.1)
sprockets (~> 2.2.1)
- activemodel (3.2.9)
- activesupport (= 3.2.9)
+ activemodel (3.2.13)
+ activesupport (= 3.2.13)
builder (~> 3.0.0)
- activerecord (3.2.9)
- activemodel (= 3.2.9)
- activesupport (= 3.2.9)
+ activerecord (3.2.13)
+ activemodel (= 3.2.13)
+ activesupport (= 3.2.13)
arel (~> 3.0.2)
tzinfo (~> 0.3.29)
- activeresource (3.2.9)
- activemodel (= 3.2.9)
- activesupport (= 3.2.9)
- activesupport (3.2.9)
- i18n (~> 0.6)
+ activeresource (3.2.13)
+ activemodel (= 3.2.13)
+ activesupport (= 3.2.13)
+ activesupport (3.2.13)
+ i18n (= 0.6.1)
multi_json (~> 1.0)
arel (3.0.2)
builder (3.0.4)
erubis (2.7.0)
- hike (1.2.1)
+ hike (1.2.2)
i18n (0.6.1)
journey (1.0.4)
- json (1.7.5)
- mail (2.4.4)
- i18n (>= 0.4.0)
+ json (1.8.0)
+ mail (2.5.4)
mime-types (~> 1.16)
treetop (~> 1.4.8)
- mime-types (1.19)
- multi_json (1.5.0)
+ mime-types (1.23)
+ multi_json (1.7.3)
polyglot (0.3.3)
- rack (1.4.1)
+ rack (1.4.5)
rack-cache (1.2)
rack (>= 0.4)
- rack-ssl (1.3.2)
+ rack-ssl (1.3.3)
rack
rack-test (0.6.2)
rack (>= 1.0)
- rails (3.2.9)
- actionmailer (= 3.2.9)
- actionpack (= 3.2.9)
- activerecord (= 3.2.9)
- activeresource (= 3.2.9)
- activesupport (= 3.2.9)
+ rails (3.2.13)
+ actionmailer (= 3.2.13)
+ actionpack (= 3.2.13)
+ activerecord (= 3.2.13)
+ activeresource (= 3.2.13)
+ activesupport (= 3.2.13)
bundler (~> 1.0)
- railties (= 3.2.9)
- railties (3.2.9)
- actionpack (= 3.2.9)
- activesupport (= 3.2.9)
+ railties (= 3.2.13)
+ railties (3.2.13)
+ actionpack (= 3.2.13)
+ activesupport (= 3.2.13)
rack-ssl (~> 1.3.2)
rake (>= 0.8.7)
rdoc (~> 3.4)
thor (>= 0.14.6, < 2.0)
- rake (10.0.3)
- rdoc (3.12)
+ rake (10.0.4)
+ rdoc (3.12.2)
json (~> 1.4)
sprockets (2.2.2)
hike (~> 1.2)
multi_json (~> 1.0)
rack (~> 1.0)
tilt (~> 1.1, != 1.3.0)
- thor (0.16.0)
- tilt (1.3.3)
+ thor (0.18.1)
+ tilt (1.4.1)
treetop (1.4.12)
polyglot
polyglot (>= 0.3.1)
- tzinfo (0.3.35)
+ tzinfo (0.3.37)
PLATFORMS
ruby
DEPENDENCIES
file_browser!
diff --git a/file_browser.gemspec b/file_browser.gemspec
index 3df4f8d..5a6e480 100644
--- a/file_browser.gemspec
+++ b/file_browser.gemspec
@@ -1,20 +1,20 @@
Gem::Specification.new do |s|
s.name = 'file_browser'
- s.version = '0.1.4'
+ s.version = '0.1.5'
s.homepage = 'http://wiki.github.com/eric1234/file_browser/'
s.author = 'Eric Anderson'
s.email = 'eric@pixelwareinc.com'
s.add_dependency 'rails', '> 3.1'
s.files = Dir['**/*'].reject do |f|
f =~ /^test/ || f == 'file_browser.gemspec' || f =~ /^pkg/
end
s.has_rdoc = true
s.extra_rdoc_files << 'README.rdoc'
s.rdoc_options << '--main' << 'README.rdoc'
s.summary = 'A Rails-gem for managing files'
s.description = <<-DESCRIPTION
Provides a web-based UI to manage a filesystem. Useful as an
alternative to FTP and also to integrate with products such
as CKEditor.
DESCRIPTION
end
|
eric1234/file_browser
|
1095b945b04fc3ddb5cbf27dcd169db71460809c
|
Use get instead of match for Rails 4 compat.
|
diff --git a/config/routes.rb b/config/routes.rb
index 58b7111..7b7d814 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,29 +1,29 @@
Rails.application.routes.draw do
# For image preview and resize on serve
if defined? Dragonfly
app = Dragonfly[:file_browser].configure_with :imagemagick
endpoint = app.endpoint do |params, app|
storage = FileBrowser.storages[params[:storage].to_sym]
file = storage[Pathname.new params[:path]]
app.fetch_file(file.stream.path).thumb params[:size]
end
- match ':storage/uploaded_files/resized/:size/(*path)' => endpoint,
+ get ':storage/uploaded_files/resized/:size/(*path)' => endpoint,
:as => :resized_uploaded_file, :format => false
end
controller :uploaded_files do
get ':storage/uploaded_files/select/:integration/(*path)' => :index,
:as => 'select_uploaded_file', :format => false
get ':storage/uploaded_files/index/(*path)' => :index,
:as => 'uploaded_files', :format => false
get ':storage/uploaded_files/(*path)' => :show,
:as => 'uploaded_file', :format => false
post ':storage/uploaded_files/drop/:integration' => :create,
:defaults => {:dropbox => true}, :as => 'drop_uploaded_file'
post ':storage/uploaded_files/(*path)' => :create,
:as => 'create_uploaded_file', :format => false
delete ':storage/uploaded_files/(*path)' => :destroy,
:as => 'delete_uploaded_file', :format => false
end
end
|
eric1234/file_browser
|
450a8c5ddedc63d3240457dc0c591ceac57cc60e
|
More updating for recent Rails
|
diff --git a/Gemfile b/Gemfile
new file mode 100644
index 0000000..e45e65f
--- /dev/null
+++ b/Gemfile
@@ -0,0 +1,2 @@
+source :rubygems
+gemspec
diff --git a/Gemfile.lock b/Gemfile.lock
new file mode 100644
index 0000000..7d2bd77
--- /dev/null
+++ b/Gemfile.lock
@@ -0,0 +1,92 @@
+PATH
+ remote: .
+ specs:
+ file_browser (0.1.4)
+ rails (> 3.1)
+
+GEM
+ remote: http://rubygems.org/
+ specs:
+ actionmailer (3.2.9)
+ actionpack (= 3.2.9)
+ mail (~> 2.4.4)
+ actionpack (3.2.9)
+ activemodel (= 3.2.9)
+ activesupport (= 3.2.9)
+ builder (~> 3.0.0)
+ erubis (~> 2.7.0)
+ journey (~> 1.0.4)
+ rack (~> 1.4.0)
+ rack-cache (~> 1.2)
+ rack-test (~> 0.6.1)
+ sprockets (~> 2.2.1)
+ activemodel (3.2.9)
+ activesupport (= 3.2.9)
+ builder (~> 3.0.0)
+ activerecord (3.2.9)
+ activemodel (= 3.2.9)
+ activesupport (= 3.2.9)
+ arel (~> 3.0.2)
+ tzinfo (~> 0.3.29)
+ activeresource (3.2.9)
+ activemodel (= 3.2.9)
+ activesupport (= 3.2.9)
+ activesupport (3.2.9)
+ i18n (~> 0.6)
+ multi_json (~> 1.0)
+ arel (3.0.2)
+ builder (3.0.4)
+ erubis (2.7.0)
+ hike (1.2.1)
+ i18n (0.6.1)
+ journey (1.0.4)
+ json (1.7.5)
+ mail (2.4.4)
+ i18n (>= 0.4.0)
+ mime-types (~> 1.16)
+ treetop (~> 1.4.8)
+ mime-types (1.19)
+ multi_json (1.5.0)
+ polyglot (0.3.3)
+ rack (1.4.1)
+ rack-cache (1.2)
+ rack (>= 0.4)
+ rack-ssl (1.3.2)
+ rack
+ rack-test (0.6.2)
+ rack (>= 1.0)
+ rails (3.2.9)
+ actionmailer (= 3.2.9)
+ actionpack (= 3.2.9)
+ activerecord (= 3.2.9)
+ activeresource (= 3.2.9)
+ activesupport (= 3.2.9)
+ bundler (~> 1.0)
+ railties (= 3.2.9)
+ railties (3.2.9)
+ actionpack (= 3.2.9)
+ activesupport (= 3.2.9)
+ rack-ssl (~> 1.3.2)
+ rake (>= 0.8.7)
+ rdoc (~> 3.4)
+ thor (>= 0.14.6, < 2.0)
+ rake (10.0.3)
+ rdoc (3.12)
+ json (~> 1.4)
+ sprockets (2.2.2)
+ hike (~> 1.2)
+ multi_json (~> 1.0)
+ rack (~> 1.0)
+ tilt (~> 1.1, != 1.3.0)
+ thor (0.16.0)
+ tilt (1.3.3)
+ treetop (1.4.12)
+ polyglot
+ polyglot (>= 0.3.1)
+ tzinfo (0.3.35)
+
+PLATFORMS
+ ruby
+
+DEPENDENCIES
+ file_browser!
diff --git a/README b/README.rdoc
similarity index 100%
rename from README
rename to README.rdoc
diff --git a/Rakefile b/Rakefile
index f2489bd..8be8118 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,28 +1,17 @@
-require 'fileutils'
-require 'rake/testtask'
-require 'rake/gempackagetask'
+require 'bundler'
+Bundler::GemHelper.install_tasks
desc 'Prepare testing by creating test app'
task :test_app do
sh "rails new test/test_app -q -m test/test_app_template.rb" unless
File.exists? 'test/test_app'
end
-spec = eval File.read('file_browser.gemspec')
-Rake::GemPackageTask.new spec do |pkg|
- pkg.need_tar = false
-end
-
-desc "Publish gem to rubygems.org"
-task :publish => :package do
- `gem push pkg/#{spec.name}-#{spec.version}.gem`
-end
-
+require 'rake/testtask'
Rake::TestTask.new(:test => :test_app) do |task|
task.libs << "lib"
task.libs << "test"
task.pattern = "test/*/*_test.rb"
task.verbose = false
end
-
task :default => :test
diff --git a/file_browser.gemspec b/file_browser.gemspec
index c3088f7..3df4f8d 100644
--- a/file_browser.gemspec
+++ b/file_browser.gemspec
@@ -1,20 +1,20 @@
Gem::Specification.new do |s|
s.name = 'file_browser'
- s.version = '0.1.2'
+ s.version = '0.1.4'
s.homepage = 'http://wiki.github.com/eric1234/file_browser/'
s.author = 'Eric Anderson'
s.email = 'eric@pixelwareinc.com'
- s.add_dependency 'rails'
+ s.add_dependency 'rails', '> 3.1'
s.files = Dir['**/*'].reject do |f|
f =~ /^test/ || f == 'file_browser.gemspec' || f =~ /^pkg/
end
s.has_rdoc = true
- s.extra_rdoc_files << 'README'
- s.rdoc_options << '--main' << 'README'
+ s.extra_rdoc_files << 'README.rdoc'
+ s.rdoc_options << '--main' << 'README.rdoc'
s.summary = 'A Rails-gem for managing files'
s.description = <<-DESCRIPTION
Provides a web-based UI to manage a filesystem. Useful as an
alternative to FTP and also to integrate with products such
as CKEditor.
DESCRIPTION
end
diff --git a/lib/file_browser.rb b/lib/file_browser.rb
index 77f4a08..b3d565b 100644
--- a/lib/file_browser.rb
+++ b/lib/file_browser.rb
@@ -1,31 +1,34 @@
module FileBrowser
# Stores all configured storages for the current app. The application
# should configure this similar to:
#
# FileBrowser.storages[:local] = FilesystemStorage.new('/path/to/root')
#
# When the browser is loaded it will have the key as the prefix. So
# for example:
#
# /local/uploaded_files
#
# Will pull the UploadedFilesController::index action using the :local
# key set above.
mattr_accessor :storages
self.storages = {}
# If set to true then the file browser provides no way to create
# directories or add files. So you can only select files. You can
# still add files via the drop functionality. This is not a security
# issue but just simplifying the interface so the file browser is
# as simple as possible.
mattr_accessor :select_only
self.select_only = false
mattr_accessor :resize
class Engine < Rails::Engine
+ initializer "file_browser.configure.assets" do |app|
+ app.config.assets.precompile += %w(file_browser.js file_browser.css)
+ end
end
end
diff --git a/test/test_app_template.rb b/test/test_app_template.rb
index 4af8e0c..a118b47 100644
--- a/test/test_app_template.rb
+++ b/test/test_app_template.rb
@@ -1,20 +1,20 @@
environment <<CONFIG
require File.join(File.dirname(__FILE__), *%w(.. .. .. lib file_browser.rb))
CONFIG
-gem 'ruby-debug'
+gem 'debugger'
initializer 'file_browser_config.rb', <<REGISTER
FileBrowser.storages[:local] =
FilesystemStorage.new Rails.root.join('../fixtures/fs_storage')
REGISTER
file 'public/javascripts/stub.js', <<JS
Event.observe(document, 'dom:loaded', function() {
Event.observe(document, 'file_browser:select', function(event) {
alert(event.memo+' selected');
});
});
JS
|
eric1234/file_browser
|
c3ae14ff7e53ac9621ec5d967b96ecac7c3a9704
|
More fixes for recent rails
|
diff --git a/config/routes.rb b/config/routes.rb
index ca9e0ba..58b7111 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,29 +1,29 @@
Rails.application.routes.draw do
# For image preview and resize on serve
if defined? Dragonfly
app = Dragonfly[:file_browser].configure_with :imagemagick
endpoint = app.endpoint do |params, app|
storage = FileBrowser.storages[params[:storage].to_sym]
file = storage[Pathname.new params[:path]]
app.fetch_file(file.stream.path).thumb params[:size]
end
match ':storage/uploaded_files/resized/:size/(*path)' => endpoint,
:as => :resized_uploaded_file, :format => false
end
controller :uploaded_files do
get ':storage/uploaded_files/select/:integration/(*path)' => :index,
- :as => 'select_uploaded_file'
+ :as => 'select_uploaded_file', :format => false
get ':storage/uploaded_files/index/(*path)' => :index,
- :as => 'uploaded_files'
+ :as => 'uploaded_files', :format => false
get ':storage/uploaded_files/(*path)' => :show,
- :as => 'uploaded_file'
+ :as => 'uploaded_file', :format => false
post ':storage/uploaded_files/drop/:integration' => :create,
:defaults => {:dropbox => true}, :as => 'drop_uploaded_file'
post ':storage/uploaded_files/(*path)' => :create,
- :as => 'create_uploaded_file'
+ :as => 'create_uploaded_file', :format => false
delete ':storage/uploaded_files/(*path)' => :destroy,
- :as => 'delete_uploaded_file'
+ :as => 'delete_uploaded_file', :format => false
end
end
diff --git a/file_browser.gemspec b/file_browser.gemspec
index 70d1b45..c3088f7 100644
--- a/file_browser.gemspec
+++ b/file_browser.gemspec
@@ -1,20 +1,20 @@
Gem::Specification.new do |s|
s.name = 'file_browser'
- s.version = '0.1.1'
+ s.version = '0.1.2'
s.homepage = 'http://wiki.github.com/eric1234/file_browser/'
s.author = 'Eric Anderson'
s.email = 'eric@pixelwareinc.com'
s.add_dependency 'rails'
s.files = Dir['**/*'].reject do |f|
f =~ /^test/ || f == 'file_browser.gemspec' || f =~ /^pkg/
end
s.has_rdoc = true
s.extra_rdoc_files << 'README'
s.rdoc_options << '--main' << 'README'
s.summary = 'A Rails-gem for managing files'
s.description = <<-DESCRIPTION
Provides a web-based UI to manage a filesystem. Useful as an
alternative to FTP and also to integrate with products such
as CKEditor.
DESCRIPTION
end
|
eric1234/file_browser
|
1d58a6ba4577bc75d5e2a3a11ed4c068d3058eac
|
Bump version
|
diff --git a/file_browser.gemspec b/file_browser.gemspec
index 8d007f1..70d1b45 100644
--- a/file_browser.gemspec
+++ b/file_browser.gemspec
@@ -1,20 +1,20 @@
Gem::Specification.new do |s|
s.name = 'file_browser'
- s.version = '0.1.0'
+ s.version = '0.1.1'
s.homepage = 'http://wiki.github.com/eric1234/file_browser/'
s.author = 'Eric Anderson'
s.email = 'eric@pixelwareinc.com'
s.add_dependency 'rails'
s.files = Dir['**/*'].reject do |f|
f =~ /^test/ || f == 'file_browser.gemspec' || f =~ /^pkg/
end
s.has_rdoc = true
s.extra_rdoc_files << 'README'
s.rdoc_options << '--main' << 'README'
s.summary = 'A Rails-gem for managing files'
s.description = <<-DESCRIPTION
Provides a web-based UI to manage a filesystem. Useful as an
alternative to FTP and also to integrate with products such
as CKEditor.
DESCRIPTION
end
|
eric1234/file_browser
|
cea05433159e8b9c0ab3719d1dc78d8201e58e10
|
Compat with Ruby 1.9 and latest Rails
|
diff --git a/app/models/filesystem_storage.rb b/app/models/filesystem_storage.rb
index ab7897e..0c601d3 100644
--- a/app/models/filesystem_storage.rb
+++ b/app/models/filesystem_storage.rb
@@ -1,75 +1,75 @@
# A storage for file on the local filesystem under a specific path.
class FilesystemStorage
# The root path of the current FileSystem storage
attr_accessor :path
# Creates a new storage located at the given path. If this path
# happens to be publically available via HTTP you can provide that
# path as well so that access the files does not have to go through
# rails.
def initialize(path, public_path=nil)
@path = Pathname.new path
@public_path = Pathname.new public_path if public_path
end
# Will retreive the UploadedFile object for the given key
def [](key)
path = @path.join key
public_path = @public_path.join key if @public_path
UploadedFile.new(key, nil, public_path) {File.open path} if path.file?
end
# Will store the given file under the given key. If the file responds
# to :read then we assume a stream. Otherwise we convert to string and
# assume a file path
def []=(key, file)
file = File.open(file.to_s) unless file.respond_to? :read
path = @path.join key
FileUtils.mkpath path.dirname
File.open(path, 'wb') {|f| f << file.read}
self[key]
end
# Like []= only creates a directory instead of a file. In stores
# that don't really support directories it might need to create
# a dummy hidden file to simulate a directory.
def mkdir(path)
path = @path.join path
FileUtils.mkpath path
end
# Works like glob but will only return directories that match.
#
# Note that the storage device does not really need to support
# directories. It could simulate it by quering the keys which is
# why this is handled somewhat differently. It allows the backend
# to optimize the directory pull (v.s. have the frontend query based
# on keys which could be inefficient).
def dirs(pattern)
Pathname.glob(@path.join(pattern)).sort.collect do |match|
path2key match if match.directory?
end.compact
end
# Will file all UploadFile objects that match the given glob pattern
def glob(pattern)
Pathname.glob(@path.join(pattern)).sort.collect do |match|
self[path2key match]
end.compact
end
# Will remove a specific key from the database. Can point to an
# UploadedFile or just a directory. If called on a file that does
# not exist then this is a no-op.
def destroy(key)
path = @path.join key
FileUtils.rm_rf path if path.exist?
end
private
def path2key(path)
- path.to_s.sub(@path, '').sub /^\//, ''
+ path.to_s.sub(@path.to_s, '').sub /^\//, ''
end
-end
\ No newline at end of file
+end
diff --git a/config/routes.rb b/config/routes.rb
index 8fed64f..ca9e0ba 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,29 +1,29 @@
Rails.application.routes.draw do
# For image preview and resize on serve
if defined? Dragonfly
app = Dragonfly[:file_browser].configure_with :imagemagick
endpoint = app.endpoint do |params, app|
storage = FileBrowser.storages[params[:storage].to_sym]
file = storage[Pathname.new params[:path]]
app.fetch_file(file.stream.path).thumb params[:size]
end
match ':storage/uploaded_files/resized/:size/(*path)' => endpoint,
- :as => :resized_uploaded_file
+ :as => :resized_uploaded_file, :format => false
end
controller :uploaded_files do
get ':storage/uploaded_files/select/:integration/(*path)' => :index,
:as => 'select_uploaded_file'
get ':storage/uploaded_files/index/(*path)' => :index,
:as => 'uploaded_files'
get ':storage/uploaded_files/(*path)' => :show,
:as => 'uploaded_file'
post ':storage/uploaded_files/drop/:integration' => :create,
:defaults => {:dropbox => true}, :as => 'drop_uploaded_file'
post ':storage/uploaded_files/(*path)' => :create,
:as => 'create_uploaded_file'
delete ':storage/uploaded_files/(*path)' => :destroy,
:as => 'delete_uploaded_file'
end
end
|
eric1234/file_browser
|
4a0671331648eed2eb557149d0037815143b60e3
|
Compatibility with Rails 3.1.
|
diff --git a/README b/README
index 7248e53..e867801 100644
--- a/README
+++ b/README
@@ -1,61 +1,61 @@
= DESCRIPTION
A rails plugin that provides a basic file browser. The primary use
case for this plugin is:
* To manage a directory of files includes subdirectories
* To integration with products like CKEditor for selecting files.
Guiding Principals:
* No database required
-* Multiple backends (filesystem, S3, etc.) - Filesystem only currently
+* Pluggable backends (filesystem, S3, etc.) - Filesystem only currently
* Pluggable integration with 3rd party products such as CKEditor
Possible Future Features:
* Launcher can specify only certain file types to show
(images only, only certain extensions, etc.)
* Allow basic image manipulation (resize, crop, etc.)
* File upload progress monitoring (for large files)
* Icon previews (mainly for images show thumbnail for icon)
= SETUP
In your Gemfile add:
gem 'file_browser'
In an initializer add:
FileBrowser.storages[:local] =
FilesystemStorage.new Rails.root.join('public/uploaded_files')
Change the above path to be wherever you want to write files. Also make
sure that directory is writable by the application.
Copy the assets to your public directory. This will likely later be
automated as Rails adds support.
Finally point your browser to /local/uploaded_files/index and start
managing your files via the web.
See example_integrations directory for how to integrate with 3rd party
tools such as CKEditor.
= CONFIGURATION
By default the app will use the "file_browser" layout. Obviously your
can override that in your application if you want. If you want it to
use the same layout as your main layout simply symlink
file_browser.html.erb to your application.html.erb file. If you use
your own layout make sure that it includes the prototype library and
that it yields to the symbol :file_browser_footer.
You can have multiple storage repositories that can be registered and
accessed. See FileBrowser#storages for more info.
= CREDIT
This gem was developed by Eric Anderson (http://pixelwareinc.com) while
developing projects under Red Tusk Studios (http://redtusk.com).
diff --git a/public/images/compressed.png b/app/assets/images/file_browser/compressed.png
similarity index 100%
rename from public/images/compressed.png
rename to app/assets/images/file_browser/compressed.png
diff --git a/public/images/contact.png b/app/assets/images/file_browser/contact.png
similarity index 100%
rename from public/images/contact.png
rename to app/assets/images/file_browser/contact.png
diff --git a/public/images/document.png b/app/assets/images/file_browser/document.png
similarity index 100%
rename from public/images/document.png
rename to app/assets/images/file_browser/document.png
diff --git a/public/images/folder.png b/app/assets/images/file_browser/folder.png
similarity index 100%
rename from public/images/folder.png
rename to app/assets/images/file_browser/folder.png
diff --git a/public/images/image.png b/app/assets/images/file_browser/image.png
similarity index 100%
rename from public/images/image.png
rename to app/assets/images/file_browser/image.png
diff --git a/public/images/internet.png b/app/assets/images/file_browser/internet.png
similarity index 100%
rename from public/images/internet.png
rename to app/assets/images/file_browser/internet.png
diff --git a/public/images/presentation.png b/app/assets/images/file_browser/presentation.png
similarity index 100%
rename from public/images/presentation.png
rename to app/assets/images/file_browser/presentation.png
diff --git a/public/images/spreadsheet.png b/app/assets/images/file_browser/spreadsheet.png
similarity index 100%
rename from public/images/spreadsheet.png
rename to app/assets/images/file_browser/spreadsheet.png
diff --git a/public/images/text.png b/app/assets/images/file_browser/text.png
similarity index 100%
rename from public/images/text.png
rename to app/assets/images/file_browser/text.png
diff --git a/public/images/unknown.png b/app/assets/images/file_browser/unknown.png
similarity index 100%
rename from public/images/unknown.png
rename to app/assets/images/file_browser/unknown.png
diff --git a/public/images/vector.png b/app/assets/images/file_browser/vector.png
similarity index 100%
rename from public/images/vector.png
rename to app/assets/images/file_browser/vector.png
diff --git a/public/images/video.png b/app/assets/images/file_browser/video.png
similarity index 100%
rename from public/images/video.png
rename to app/assets/images/file_browser/video.png
diff --git a/public/javascripts/file_browser.js b/app/assets/javascripts/file_browser.js
similarity index 100%
rename from public/javascripts/file_browser.js
rename to app/assets/javascripts/file_browser.js
diff --git a/public/stylesheets/file_browser.css b/app/assets/stylesheets/file_browser.css
similarity index 100%
rename from public/stylesheets/file_browser.css
rename to app/assets/stylesheets/file_browser.css
diff --git a/app/controllers/uploaded_files_controller.rb b/app/controllers/uploaded_files_controller.rb
index b2f9f4b..7e521de 100644
--- a/app/controllers/uploaded_files_controller.rb
+++ b/app/controllers/uploaded_files_controller.rb
@@ -1,57 +1,57 @@
class UploadedFilesController < ApplicationController
layout 'file_browser'
skip_before_filter :verify_authenticity_token, :only => :create
# Will display all files in the given directory
def index
- params[:path] = ['.'] if params[:path].blank?
- @path = Pathname.new params[:path].join '/'
+ params[:path] = '.' if params[:path].blank?
+ @path = Pathname.new params[:path]
@current_directory = @path.basename.to_s
@current_directory = 'Root Directory' if @current_directory == '.'
pattern = "#{@path}/*"
@directories = @storage.dirs pattern
@uploaded_files = @storage.glob pattern
end
# Will stream a specific file out. This should only be used if
# the file does not have a public_path.
def show
- uploaded_file = @storage[Pathname.new params[:path].join '/']
+ uploaded_file = @storage[Pathname.new params[:path]]
if uploaded_file
send_data uploaded_file.stream.read, :filename => uploaded_file.to_s
else
render :nothing => true, :status => :not_found
end
end
# Will create a new entry in the given path. If the data is a string
# then we assume a directory is being created. If the data is some
# sort of IO object then we assume a file.
def create
params[:data] = params[:upload] if params.has_key? :upload # For CKEditor
if params[:data].respond_to?(:read)
filename = File.basename(params[:data].original_filename)
- filename = Pathname.new(params[:path].join('/')).join filename
+ filename = Pathname.new(params[:path] || '').join filename
@storage[filename] = params[:data]
@uploaded_file = @storage[filename]
else
- path = Pathname.new(params[:path].join('/')).join params[:data]
+ path = Pathname.new(params[:path] || '').join params[:data]
@storage.mkdir path
end
redirect_to :back unless params[:dropbox]
end
# Removes a specific file
def destroy
- @storage.destroy params[:path].join('/')
+ @storage.destroy params[:path]
redirect_to :back
end
private
def load_storage
@storage = FileBrowser.storages[params[:storage].to_sym]
end
before_filter :load_storage
end
diff --git a/app/helpers/uploaded_files_helper.rb b/app/helpers/uploaded_files_helper.rb
index 87e9048..a94b1cd 100644
--- a/app/helpers/uploaded_files_helper.rb
+++ b/app/helpers/uploaded_files_helper.rb
@@ -1,59 +1,55 @@
module UploadedFilesHelper
def link_to_up(label='..', path=@path)
return if path.to_s == '.'
name = path.dirname
name = 'Root Directory' if name.to_s == '.'
label = label.sub '?', name
- link_to_directory path.dirname, label, :id => 'up-dir'
+ link_to_directory path.dirname, label.html_safe, :id => 'up-dir'
end
def link_to_directory(dir, label=File.basename(dir), options={})
path = params.merge({
:controller => 'uploaded_files',
:action => 'index',
- :path => to_parts(dir),
+ :path => dir,
:integration => params[:integration]
})
link_to label, path, options
end
def link_to_uploaded_file(file, label=file.to_s)
link_to label, path_to_uploaded_file(file)
end
def path_to_uploaded_file(file)
- if file.public_path
- if FileBrowser.resize && defined?(AssetProcess) && (file.general_type == 'image')
- file.public_path.to_s + '.resized/' + FileBrowser.resize
- else
+ if FileBrowser.resize && defined?(Dragonfly) && (file.general_type == 'image')
+ resized_uploaded_file_path :path => file.path, :size => FileBrowser.resize
+ else
+ if file.public_path
file.public_path
+ else
+ uploaded_file_path :path => file.path
end
- else
- uploaded_file_path :path => to_parts(file.path)
end.to_s
end
def uploaded_file_form_tag(&blk)
- path = create_uploaded_file_path :path => to_parts(@path)
+ path = create_uploaded_file_path :path => @path
form_tag path, :multipart => true, &blk
end
def link_to_destroy(path, label='X')
- button_to label, delete_uploaded_file_path(:path => to_parts(path)), :method => :delete
- end
-
- def to_parts(path)
- path.to_s.split('/').reject &:blank?
+ button_to label, delete_uploaded_file_path(:path => path), :method => :delete
end
def icon_for(file)
- if defined?(AssetProcess) && file.public_path && (file.general_type == 'image')
- file.public_path.to_s + '.resized/pad/128x128'
+ if defined?(Dragonfly) && (file.general_type == 'image')
+ resized_uploaded_file_path :path => file.path, :size => '128x128'
else
"file_browser/#{file.general_type}.png"
end
end
end
diff --git a/config/routes.rb b/config/routes.rb
index e76ceec..8fed64f 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,17 +1,29 @@
Rails.application.routes.draw do
+
+ # For image preview and resize on serve
+ if defined? Dragonfly
+ app = Dragonfly[:file_browser].configure_with :imagemagick
+ endpoint = app.endpoint do |params, app|
+ storage = FileBrowser.storages[params[:storage].to_sym]
+ file = storage[Pathname.new params[:path]]
+ app.fetch_file(file.stream.path).thumb params[:size]
+ end
+ match ':storage/uploaded_files/resized/:size/(*path)' => endpoint,
+ :as => :resized_uploaded_file
+ end
+
controller :uploaded_files do
get ':storage/uploaded_files/select/:integration/(*path)' => :index,
:as => 'select_uploaded_file'
get ':storage/uploaded_files/index/(*path)' => :index,
:as => 'uploaded_files'
get ':storage/uploaded_files/(*path)' => :show,
:as => 'uploaded_file'
post ':storage/uploaded_files/drop/:integration' => :create,
- :defaults => {:path => [], :dropbox => true},
- :as => 'drop_uploaded_file'
+ :defaults => {:dropbox => true}, :as => 'drop_uploaded_file'
post ':storage/uploaded_files/(*path)' => :create,
:as => 'create_uploaded_file'
delete ':storage/uploaded_files/(*path)' => :destroy,
:as => 'delete_uploaded_file'
end
end
diff --git a/file_browser.gemspec b/file_browser.gemspec
index e3a6981..8d007f1 100644
--- a/file_browser.gemspec
+++ b/file_browser.gemspec
@@ -1,20 +1,20 @@
Gem::Specification.new do |s|
s.name = 'file_browser'
- s.version = '0.0.5'
+ s.version = '0.1.0'
s.homepage = 'http://wiki.github.com/eric1234/file_browser/'
s.author = 'Eric Anderson'
s.email = 'eric@pixelwareinc.com'
s.add_dependency 'rails'
s.files = Dir['**/*'].reject do |f|
f =~ /^test/ || f == 'file_browser.gemspec' || f =~ /^pkg/
end
s.has_rdoc = true
s.extra_rdoc_files << 'README'
s.rdoc_options << '--main' << 'README'
s.summary = 'A Rails-gem for managing files'
s.description = <<-DESCRIPTION
Provides a web-based UI to manage a filesystem. Useful as an
alternative to FTP and also to integrate with products such
as CKEditor.
DESCRIPTION
end
diff --git a/test/functional/uploaded_files_controller_test.rb b/test/functional/uploaded_files_controller_test.rb
index 700c3d1..f2041bd 100644
--- a/test/functional/uploaded_files_controller_test.rb
+++ b/test/functional/uploaded_files_controller_test.rb
@@ -1,179 +1,179 @@
require 'test_helper'
class UploadedFilesControllerTest < ActionController::TestCase
test 'root directory' do
- get :index, :path => [], :storage => 'local'
+ get :index, :storage => 'local'
assert_response :success
assert_select 'h1', 'Root Directory'
assert_select 'a', :text => /Return to/, :count => 0
assert_select 'li', 4
assert_select 'a[href=?]', '/local/uploaded_files/index/dir1'
assert_select 'form[action=?]', '/local/uploaded_files/dir1'
assert_select 'a[href=?]', '/local/uploaded_files/index/empty'
assert_select 'form[action=?]', '/local/uploaded_files/empty'
assert_select 'a[href=?]', '/local/uploaded_files/file1.txt'
assert_select 'form[action=?]', '/local/uploaded_files/file1.txt'
assert_select 'a[href=?]', '/local/uploaded_files/file2.txt'
assert_select 'form[action=?]', '/local/uploaded_files/file2.txt'
end
test 'empty directory' do
- get :index, :path => ['empty'], :storage => 'local'
+ get :index, :path => 'empty', :storage => 'local'
assert_response :success
assert_select 'h1', 'empty'
assert_select 'a', /Return to Root Directory/
assert_select 'li', 0
end
test 'subdirectory' do
- get :index, :path => ['dir1'], :storage => 'local'
+ get :index, :path => 'dir1', :storage => 'local'
assert_response :success
assert_select 'h1', 'dir1'
assert_select 'a', /Return to Root Directory/
assert_select 'li', 2
assert_select 'a[href=?]', '/local/uploaded_files/index/dir1/subdir'
assert_select 'form[action=?]', '/local/uploaded_files/dir1/subdir'
assert_select 'a[href=?]', '/local/uploaded_files/dir1/subfile1.txt'
assert_select 'form[action=?]', '/local/uploaded_files/dir1/subfile1.txt'
end
test 'sub of sub' do
- get :index, :path => ['dir1', 'subdir'], :storage => 'local'
+ get :index, :path => 'dir1/subdir', :storage => 'local'
assert_response :success
assert_select 'h1', 'subdir'
assert_select 'a', /Return to dir1/
assert_select 'li', 0
end
test 'show (root directory)' do
- get :show, :path => ['file1.txt'], :storage => 'local'
+ get :show, :path => 'file1.txt', :storage => 'local'
assert_response :success
assert_equal 'File 1', @response.body
end
test 'show (subdir)' do
- get :show, :path => ['dir1', 'subfile1.txt'], :storage => 'local'
+ get :show, :path => 'dir1/subfile1.txt', :storage => 'local'
assert_response :success
assert_equal 'File in subdirectory.', @response.body
end
test 'show (404)' do
- get :show, :path => ['foo.txt'], :storage => 'local'
+ get :show, :path => 'foo.txt', :storage => 'local'
assert_response :not_found
end
test 'create folder (root directory)' do
dest = storage_path.join 'foo'
FileUtils.rmdir dest if dest.exist?
assert !dest.exist?
@request.env["HTTP_REFERER"] = '/local/uploaded_files/index'
- post :create, :path => [], :data => 'foo', :storage => 'local'
+ post :create, :data => 'foo', :storage => 'local'
assert dest.directory?
FileUtils.rmdir dest if dest.exist?
end
test 'create folder (subdirectory)' do
dest = storage_path.join 'dir1/foo'
FileUtils.rmdir dest if dest.exist?
assert !dest.exist?
@request.env["HTTP_REFERER"] = '/local/uploaded_files/index/dir1'
- post :create, :path => ['dir1'], :data => 'foo', :storage => 'local'
+ post :create, :path => 'dir1', :data => 'foo', :storage => 'local'
assert dest.directory?
FileUtils.rmdir dest if dest.exist?
end
test 'create file (root directory)' do
dest = storage_path.join 'foo.txt'
FileUtils.rm dest if dest.exist?
assert !dest.exist?
@request.env["HTTP_REFERER"] = '/local/uploaded_files/index'
file = StringIO.new('Test content')
def file.original_filename; 'foo.txt' end
- post :create, :path => [], :data => file, :storage => 'local'
+ post :create, :data => file, :storage => 'local'
assert dest.exist?
FileUtils.rm dest if dest.exist?
end
test 'create file (subdirectory)' do
dest = storage_path.join 'dir1/foo.txt'
FileUtils.rm dest if dest.exist?
assert !dest.exist?
@request.env["HTTP_REFERER"] = '/local/uploaded_files/index/dir1'
file = StringIO.new('Test content')
def file.original_filename; 'foo.txt' end
- post :create, :path => ['dir1'], :data => file, :storage => 'local'
+ post :create, :path => 'dir1', :data => file, :storage => 'local'
assert dest.exist?
FileUtils.rm dest if dest.exist?
end
test 'remove file (root directory)' do
dest = storage_path.join 'foo.txt'
File.open(dest, 'w+') {|f| f << 'Remove me'}
assert dest.exist?
@request.env["HTTP_REFERER"] = '/local/uploaded_files/index'
- delete :destroy, :path => ['foo.txt'], :storage => 'local'
+ delete :destroy, :path => 'foo.txt', :storage => 'local'
assert !dest.exist?
end
test 'remove file (sub-directory)' do
dest = storage_path.join 'dir1/foo.txt'
File.open(dest, 'w+') {|f| f << 'Remove me'}
assert dest.exist?
@request.env["HTTP_REFERER"] = '/local/uploaded_files/index/dir1'
- delete :destroy, :path => ['dir1', 'foo.txt'], :storage => 'local'
+ delete :destroy, :path => 'dir1/foo.txt', :storage => 'local'
assert !dest.exist?
end
test 'remove directory (root directory)' do
dest = storage_path.join 'bar'
dest.mkpath
assert dest.directory?
@request.env["HTTP_REFERER"] = '/local/uploaded_files/index'
- delete :destroy, :path => ['bar'], :storage => 'local'
+ delete :destroy, :path => 'bar', :storage => 'local'
assert !dest.exist?
end
test 'remove directory (sub-directory)' do
dest = storage_path.join 'dir1/bar'
dest.mkpath
assert dest.directory?
@request.env["HTTP_REFERER"] = '/local/uploaded_files/index/dir1'
- delete :destroy, :path => ['dir1', 'bar'], :storage => 'local'
+ delete :destroy, :path => 'dir1/bar', :storage => 'local'
assert !dest.exist?
end
def setup
# Somehow this is getting cleared so reset it for testing
FileBrowser.storages[:local] = FilesystemStorage.new storage_path
end
private
def storage_path
Pathname.new(__FILE__).dirname.join '../fixtures/fs_storage'
end
end
|
eric1234/file_browser
|
d07ed41df9b7104c8b46f4e925ca694ba40c3ebe
|
Reize fix
|
diff --git a/app/helpers/uploaded_files_helper.rb b/app/helpers/uploaded_files_helper.rb
index 3abd27b..87e9048 100644
--- a/app/helpers/uploaded_files_helper.rb
+++ b/app/helpers/uploaded_files_helper.rb
@@ -1,59 +1,59 @@
module UploadedFilesHelper
def link_to_up(label='..', path=@path)
return if path.to_s == '.'
name = path.dirname
name = 'Root Directory' if name.to_s == '.'
label = label.sub '?', name
link_to_directory path.dirname, label, :id => 'up-dir'
end
def link_to_directory(dir, label=File.basename(dir), options={})
path = params.merge({
:controller => 'uploaded_files',
:action => 'index',
:path => to_parts(dir),
:integration => params[:integration]
})
link_to label, path, options
end
def link_to_uploaded_file(file, label=file.to_s)
link_to label, path_to_uploaded_file(file)
end
def path_to_uploaded_file(file)
if file.public_path
if FileBrowser.resize && defined?(AssetProcess) && (file.general_type == 'image')
- file.public_path + FileBrowser.resize
+ file.public_path.to_s + '.resized/' + FileBrowser.resize
else
file.public_path
end
else
uploaded_file_path :path => to_parts(file.path)
end.to_s
end
def uploaded_file_form_tag(&blk)
path = create_uploaded_file_path :path => to_parts(@path)
form_tag path, :multipart => true, &blk
end
def link_to_destroy(path, label='X')
button_to label, delete_uploaded_file_path(:path => to_parts(path)), :method => :delete
end
def to_parts(path)
path.to_s.split('/').reject &:blank?
end
def icon_for(file)
if defined?(AssetProcess) && file.public_path && (file.general_type == 'image')
- (file.public_path+'pad/128x128').to_s
+ file.public_path.to_s + '.resized/pad/128x128'
else
"file_browser/#{file.general_type}.png"
end
end
end
diff --git a/file_browser.gemspec b/file_browser.gemspec
index 6b6ade1..e3a6981 100644
--- a/file_browser.gemspec
+++ b/file_browser.gemspec
@@ -1,20 +1,20 @@
Gem::Specification.new do |s|
s.name = 'file_browser'
- s.version = '0.0.4'
+ s.version = '0.0.5'
s.homepage = 'http://wiki.github.com/eric1234/file_browser/'
s.author = 'Eric Anderson'
s.email = 'eric@pixelwareinc.com'
s.add_dependency 'rails'
s.files = Dir['**/*'].reject do |f|
f =~ /^test/ || f == 'file_browser.gemspec' || f =~ /^pkg/
end
s.has_rdoc = true
s.extra_rdoc_files << 'README'
s.rdoc_options << '--main' << 'README'
s.summary = 'A Rails-gem for managing files'
s.description = <<-DESCRIPTION
Provides a web-based UI to manage a filesystem. Useful as an
alternative to FTP and also to integrate with products such
as CKEditor.
DESCRIPTION
end
|
eric1234/file_browser
|
c5da6f33d4d15d838b8f14abd061ee5f32b6a22c
|
Added start of support for resizing images on insert. Also preview images.
|
diff --git a/app/helpers/uploaded_files_helper.rb b/app/helpers/uploaded_files_helper.rb
index fc594ad..3abd27b 100644
--- a/app/helpers/uploaded_files_helper.rb
+++ b/app/helpers/uploaded_files_helper.rb
@@ -1,40 +1,59 @@
module UploadedFilesHelper
def link_to_up(label='..', path=@path)
return if path.to_s == '.'
name = path.dirname
name = 'Root Directory' if name.to_s == '.'
label = label.sub '?', name
link_to_directory path.dirname, label, :id => 'up-dir'
end
def link_to_directory(dir, label=File.basename(dir), options={})
path = params.merge({
:controller => 'uploaded_files',
:action => 'index',
:path => to_parts(dir),
:integration => params[:integration]
})
link_to label, path, options
end
def link_to_uploaded_file(file, label=file.to_s)
- url = file.public_path || uploaded_file_path(:path => to_parts(file.path))
- link_to label, url.to_s
+ link_to label, path_to_uploaded_file(file)
+ end
+
+ def path_to_uploaded_file(file)
+ if file.public_path
+ if FileBrowser.resize && defined?(AssetProcess) && (file.general_type == 'image')
+ file.public_path + FileBrowser.resize
+ else
+ file.public_path
+ end
+ else
+ uploaded_file_path :path => to_parts(file.path)
+ end.to_s
end
def uploaded_file_form_tag(&blk)
path = create_uploaded_file_path :path => to_parts(@path)
form_tag path, :multipart => true, &blk
end
def link_to_destroy(path, label='X')
button_to label, delete_uploaded_file_path(:path => to_parts(path)), :method => :delete
end
def to_parts(path)
path.to_s.split('/').reject &:blank?
end
-end
\ No newline at end of file
+ def icon_for(file)
+ if defined?(AssetProcess) && file.public_path && (file.general_type == 'image')
+ (file.public_path+'pad/128x128').to_s
+ else
+ "file_browser/#{file.general_type}.png"
+ end
+ end
+
+end
diff --git a/app/models/uploaded_file.rb b/app/models/uploaded_file.rb
index b00a007..8366e2d 100644
--- a/app/models/uploaded_file.rb
+++ b/app/models/uploaded_file.rb
@@ -1,63 +1,63 @@
class UploadedFile
attr_reader :path, :public_path, :mime_type
MIME_MAP = {
'compressed' => [/zip/, /tar/, /compress/],
'contact' => [/vcard/],
'document' => [/word/, /document/, /pdf/],
'image' => [/image/, /graphic/],
'presentation' => [/powerpoint/, /presentation/],
'spreadhseet' => [/excel/, /spreadsheet/],
'vector' => [/svg/, /flash/],
'video' => [/video/],
# Put XML towards the end as it might capture others
'internet' => [/html/, /xml/],
# Put text VERY last as it might capture html
'text' => [/text/],
}
EXTENSION_MAP = {
'compressed' => %w(zip gz tar z tgz),
'contact' => %w(vcf),
'document' => %w(doc docx dot dotx odt pdf),
'image' => %w(odg png gif jpg jpeg tiff bmp),
'internet' => %w(html xml),
'presentation' => %w(ppt pptx odp),
'spreadsheet' => %w(xls xlsx ods),
'text' => %w(txt text),
'vector' => %w(svg swf),
'video' => %w(flv mov avi mpeg mpg )
}
def initialize(path, mime_type='application/octet-stream', public_path=nil, &blk) # :nodoc:
- @path = path
+ @path = path.to_s
@mime_type = mime_type
@public_path = public_path
@retrieve = blk
end
def general_type
MIME_MAP.each do |gt, types|
return gt if types.any? {|t| t =~ mime_type}
end
EXTENSION_MAP.each do |gt, extensions|
return gt if extensions.any? {|e| e == extension}
end
return 'unknown'
end
def extension
return unless path =~ /\./
path.split('.').last.downcase
end
def to_s
File.basename path.to_s
end
# Will return a stream that can be used to read the resource
def stream
@retrieve.call
end
-end
\ No newline at end of file
+end
diff --git a/app/views/uploaded_files/create.html.erb b/app/views/uploaded_files/create.html.erb
index bfb4cf1..07414f0 100644
--- a/app/views/uploaded_files/create.html.erb
+++ b/app/views/uploaded_files/create.html.erb
@@ -1,10 +1,8 @@
-<% content_for :file_browser_footer do
- path = @uploaded_file.public_path ||
- uploaded_file_path(:path => to_parts(@uploaded_file.path)) %>
+<% content_for :file_browser_footer do %>
<%= javascript_include_tag params[:integration] %>
<%= javascript_tag %Q{
Event.observe(document, 'dom:loaded', function() {
- document.fire('file_browser:select', '#{path.to_s}');
+ document.fire('file_browser:select', '#{path_to_uploaded_file @uploaded_file}');
});
} %>
-<% end %>
\ No newline at end of file
+<% end %>
diff --git a/app/views/uploaded_files/index.html.erb b/app/views/uploaded_files/index.html.erb
index b2eadf6..c7b1bf1 100644
--- a/app/views/uploaded_files/index.html.erb
+++ b/app/views/uploaded_files/index.html.erb
@@ -1,42 +1,42 @@
<% unless FileBrowser.select_only %>
<h1><%= @current_directory %></h1>
<fieldset id="upload-forms">
<legend>Add New Content</legend>
<%= uploaded_file_form_tag do %>
<label for="file_data">Upload File</label>
<%= file_field_tag :data, :id => 'file_data' %>
<%= submit_tag 'Upload' %>
<% end %>
<%= uploaded_file_form_tag do %>
<label for="directory_data">Create Directory</label>
<%= text_field_tag :data, nil, :id => 'directory_data' %>
<%= submit_tag 'Create' %>
<% end %>
</fieldset>
<%= link_to_up "« Return to ?" %>
<% end %>
<ul id="directory-index" class="<%= 'clickable' if params[:integration] %>">
<% for directory in @directories %>
<li class="directory">
<%= image_tag "file_browser/folder.png", :alt => '' %>
<%= link_to_directory directory %>
<%= link_to_destroy directory %>
</li>
<% end %>
<% for file in @uploaded_files %>
<li class="file">
- <%= image_tag "file_browser/#{file.general_type}.png", :alt => '' %>
+ <%= image_tag icon_for(file), :alt => '' %>
<%= link_to_uploaded_file file %>
<%= link_to_destroy file.path %>
</li>
<% end %>
</ul>
<% content_for :file_browser_footer do %>
<%= javascript_include_tag params[:integration] %>
<% end if params[:integration] %>
diff --git a/file_browser.gemspec b/file_browser.gemspec
index 2f2178c..6b6ade1 100644
--- a/file_browser.gemspec
+++ b/file_browser.gemspec
@@ -1,20 +1,20 @@
Gem::Specification.new do |s|
s.name = 'file_browser'
- s.version = '0.0.3'
+ s.version = '0.0.4'
s.homepage = 'http://wiki.github.com/eric1234/file_browser/'
s.author = 'Eric Anderson'
s.email = 'eric@pixelwareinc.com'
s.add_dependency 'rails'
s.files = Dir['**/*'].reject do |f|
f =~ /^test/ || f == 'file_browser.gemspec' || f =~ /^pkg/
end
s.has_rdoc = true
s.extra_rdoc_files << 'README'
s.rdoc_options << '--main' << 'README'
s.summary = 'A Rails-gem for managing files'
s.description = <<-DESCRIPTION
Provides a web-based UI to manage a filesystem. Useful as an
alternative to FTP and also to integrate with products such
as CKEditor.
DESCRIPTION
end
diff --git a/lib/file_browser.rb b/lib/file_browser.rb
index bdd887c..77f4a08 100644
--- a/lib/file_browser.rb
+++ b/lib/file_browser.rb
@@ -1,29 +1,31 @@
module FileBrowser
# Stores all configured storages for the current app. The application
# should configure this similar to:
#
# FileBrowser.storages[:local] = FilesystemStorage.new('/path/to/root')
#
# When the browser is loaded it will have the key as the prefix. So
# for example:
#
# /local/uploaded_files
#
# Will pull the UploadedFilesController::index action using the :local
# key set above.
mattr_accessor :storages
self.storages = {}
# If set to true then the file browser provides no way to create
# directories or add files. So you can only select files. You can
# still add files via the drop functionality. This is not a security
# issue but just simplifying the interface so the file browser is
# as simple as possible.
mattr_accessor :select_only
self.select_only = false
+ mattr_accessor :resize
+
class Engine < Rails::Engine
end
end
|
eric1234/file_browser
|
e41f7561eb4383762ea3eef2b5978cf44b160e1e
|
Rails 3 support. Rails 2.x support dropped.
|
diff --git a/README b/README
index e3d1929..7248e53 100644
--- a/README
+++ b/README
@@ -1,63 +1,61 @@
= DESCRIPTION
A rails plugin that provides a basic file browser. The primary use
case for this plugin is:
* To manage a directory of files includes subdirectories
* To integration with products like CKEditor for selecting files.
Guiding Principals:
* No database required
* Multiple backends (filesystem, S3, etc.) - Filesystem only currently
* Pluggable integration with 3rd party products such as CKEditor
Possible Future Features:
* Launcher can specify only certain file types to show
(images only, only certain extensions, etc.)
* Allow basic image manipulation (resize, crop, etc.)
* File upload progress monitoring (for large files)
+* Icon previews (mainly for images show thumbnail for icon)
= SETUP
-In your environment.rb add:
+In your Gemfile add:
- config.gem 'file_browser'
+ gem 'file_browser'
In an initializer add:
FileBrowser.storages[:local] =
FilesystemStorage.new Rails.root.join('public/uploaded_files')
Change the above path to be wherever you want to write files. Also make
sure that directory is writable by the application.
-Next run `rake file_browser:assets:copy` to copy the necessary
-javascript, CSS and images to your public directory. You can feel free
-to update those files. The copy only happens when you run the rake task.
-Note that you need to put `require 'file_browser/rails_tasks'` in your
-Rakefile for the rake tasks to be included in your app.
+Copy the assets to your public directory. This will likely later be
+automated as Rails adds support.
Finally point your browser to /local/uploaded_files/index and start
managing your files via the web.
See example_integrations directory for how to integrate with 3rd party
tools such as CKEditor.
= CONFIGURATION
By default the app will use the "file_browser" layout. Obviously your
can override that in your application if you want. If you want it to
use the same layout as your main layout simply symlink
file_browser.html.erb to your application.html.erb file. If you use
your own layout make sure that it includes the prototype library and
that it yields to the symbol :file_browser_footer.
You can have multiple storage repositories that can be registered and
accessed. See FileBrowser#storages for more info.
= CREDIT
This gem was developed by Eric Anderson (http://pixelwareinc.com) while
developing projects under Red Tusk Studios (http://redtusk.com).
diff --git a/Rakefile b/Rakefile
index eab3c02..f2489bd 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,28 +1,28 @@
require 'fileutils'
require 'rake/testtask'
require 'rake/gempackagetask'
desc 'Prepare testing by creating test app'
task :test_app do
- sh "rails _2.3.9_ -q -m test/test_app_template.rb test/test_app" unless
+ sh "rails new test/test_app -q -m test/test_app_template.rb" unless
File.exists? 'test/test_app'
end
spec = eval File.read('file_browser.gemspec')
Rake::GemPackageTask.new spec do |pkg|
pkg.need_tar = false
end
desc "Publish gem to rubygems.org"
task :publish => :package do
`gem push pkg/#{spec.name}-#{spec.version}.gem`
end
Rake::TestTask.new(:test => :test_app) do |task|
task.libs << "lib"
task.libs << "test"
task.pattern = "test/*/*_test.rb"
task.verbose = false
end
task :default => :test
diff --git a/app/controllers/uploaded_files_controller.rb b/app/controllers/uploaded_files_controller.rb
index 3e6abce..b2f9f4b 100644
--- a/app/controllers/uploaded_files_controller.rb
+++ b/app/controllers/uploaded_files_controller.rb
@@ -1,57 +1,57 @@
class UploadedFilesController < ApplicationController
layout 'file_browser'
skip_before_filter :verify_authenticity_token, :only => :create
# Will display all files in the given directory
def index
params[:path] = ['.'] if params[:path].blank?
@path = Pathname.new params[:path].join '/'
@current_directory = @path.basename.to_s
@current_directory = 'Root Directory' if @current_directory == '.'
pattern = "#{@path}/*"
@directories = @storage.dirs pattern
@uploaded_files = @storage.glob pattern
end
# Will stream a specific file out. This should only be used if
# the file does not have a public_path.
def show
uploaded_file = @storage[Pathname.new params[:path].join '/']
if uploaded_file
send_data uploaded_file.stream.read, :filename => uploaded_file.to_s
else
render :nothing => true, :status => :not_found
end
end
# Will create a new entry in the given path. If the data is a string
# then we assume a directory is being created. If the data is some
# sort of IO object then we assume a file.
def create
params[:data] = params[:upload] if params.has_key? :upload # For CKEditor
if params[:data].respond_to?(:read)
filename = File.basename(params[:data].original_filename)
filename = Pathname.new(params[:path].join('/')).join filename
@storage[filename] = params[:data]
@uploaded_file = @storage[filename]
else
path = Pathname.new(params[:path].join('/')).join params[:data]
@storage.mkdir path
end
redirect_to :back unless params[:dropbox]
end
# Removes a specific file
def destroy
@storage.destroy params[:path].join('/')
redirect_to :back
end
private
def load_storage
@storage = FileBrowser.storages[params[:storage].to_sym]
end
before_filter :load_storage
-end
\ No newline at end of file
+end
diff --git a/app/views/uploaded_files/index.html.erb b/app/views/uploaded_files/index.html.erb
index 2b9544b..b2eadf6 100644
--- a/app/views/uploaded_files/index.html.erb
+++ b/app/views/uploaded_files/index.html.erb
@@ -1,42 +1,42 @@
<% unless FileBrowser.select_only %>
<h1><%= @current_directory %></h1>
<fieldset id="upload-forms">
<legend>Add New Content</legend>
- <% uploaded_file_form_tag do %>
+ <%= uploaded_file_form_tag do %>
<label for="file_data">Upload File</label>
<%= file_field_tag :data, :id => 'file_data' %>
<%= submit_tag 'Upload' %>
<% end %>
- <% uploaded_file_form_tag do %>
+ <%= uploaded_file_form_tag do %>
<label for="directory_data">Create Directory</label>
<%= text_field_tag :data, nil, :id => 'directory_data' %>
<%= submit_tag 'Create' %>
<% end %>
</fieldset>
<%= link_to_up "« Return to ?" %>
<% end %>
<ul id="directory-index" class="<%= 'clickable' if params[:integration] %>">
<% for directory in @directories %>
<li class="directory">
<%= image_tag "file_browser/folder.png", :alt => '' %>
<%= link_to_directory directory %>
<%= link_to_destroy directory %>
</li>
<% end %>
<% for file in @uploaded_files %>
<li class="file">
<%= image_tag "file_browser/#{file.general_type}.png", :alt => '' %>
<%= link_to_uploaded_file file %>
<%= link_to_destroy file.path %>
</li>
<% end %>
</ul>
<% content_for :file_browser_footer do %>
<%= javascript_include_tag params[:integration] %>
<% end if params[:integration] %>
diff --git a/config/routes.rb b/config/routes.rb
index 3e9b365..e76ceec 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,20 +1,17 @@
-ActionController::Routing::Routes.draw do |map|
- map.select_uploaded_file ':storage/uploaded_files/select/:integration/*path',
- :controller => 'uploaded_files', :action => 'index',
- :conditions => {:method => :get}
- map.uploaded_files ':storage/uploaded_files/index/*path',
- :controller => 'uploaded_files', :action => 'index',
- :conditions => {:method => :get}
- map.uploaded_file ':storage/uploaded_files/*path',
- :controller => 'uploaded_files', :action => 'show',
- :conditions => {:method => :get}
- map.drop_uploaded_file ':storage/uploaded_files/drop/:integration',
- :controller => 'uploaded_files', :action => 'create',
- :path => [], :dropbox => true, :conditions => {:method => :post}
- map.create_uploaded_file ':storage/uploaded_files/*path',
- :controller => 'uploaded_files', :action => 'create',
- :conditions => {:method => :post}
- map.delete_uploaded_file ':storage/uploaded_files/*path',
- :controller => 'uploaded_files', :action => 'destroy',
- :conditions => {:method => :delete}
-end
\ No newline at end of file
+Rails.application.routes.draw do
+ controller :uploaded_files do
+ get ':storage/uploaded_files/select/:integration/(*path)' => :index,
+ :as => 'select_uploaded_file'
+ get ':storage/uploaded_files/index/(*path)' => :index,
+ :as => 'uploaded_files'
+ get ':storage/uploaded_files/(*path)' => :show,
+ :as => 'uploaded_file'
+ post ':storage/uploaded_files/drop/:integration' => :create,
+ :defaults => {:path => [], :dropbox => true},
+ :as => 'drop_uploaded_file'
+ post ':storage/uploaded_files/(*path)' => :create,
+ :as => 'create_uploaded_file'
+ delete ':storage/uploaded_files/(*path)' => :destroy,
+ :as => 'delete_uploaded_file'
+ end
+end
diff --git a/file_browser.gemspec b/file_browser.gemspec
index 50fdcee..2f2178c 100644
--- a/file_browser.gemspec
+++ b/file_browser.gemspec
@@ -1,20 +1,20 @@
Gem::Specification.new do |s|
s.name = 'file_browser'
- s.version = '0.0.2'
+ s.version = '0.0.3'
s.homepage = 'http://wiki.github.com/eric1234/file_browser/'
s.author = 'Eric Anderson'
s.email = 'eric@pixelwareinc.com'
s.add_dependency 'rails'
s.files = Dir['**/*'].reject do |f|
f =~ /^test/ || f == 'file_browser.gemspec' || f =~ /^pkg/
end
s.has_rdoc = true
s.extra_rdoc_files << 'README'
s.rdoc_options << '--main' << 'README'
s.summary = 'A Rails-gem for managing files'
s.description = <<-DESCRIPTION
Provides a web-based UI to manage a filesystem. Useful as an
alternative to FTP and also to integrate with products such
as CKEditor.
DESCRIPTION
end
diff --git a/lib/file_browser.rb b/lib/file_browser.rb
index 65ba6f5..bdd887c 100644
--- a/lib/file_browser.rb
+++ b/lib/file_browser.rb
@@ -1,26 +1,29 @@
module FileBrowser
# Stores all configured storages for the current app. The application
# should configure this similar to:
#
# FileBrowser.storages[:local] = FilesystemStorage.new('/path/to/root')
#
# When the browser is loaded it will have the key as the prefix. So
# for example:
#
# /local/uploaded_files
#
# Will pull the UploadedFilesController::index action using the :local
# key set above.
mattr_accessor :storages
self.storages = {}
# If set to true then the file browser provides no way to create
# directories or add files. So you can only select files. You can
# still add files via the drop functionality. This is not a security
# issue but just simplifying the interface so the file browser is
# as simple as possible.
mattr_accessor :select_only
self.select_only = false
+ class Engine < Rails::Engine
+ end
+
end
diff --git a/lib/file_browser/rails_tasks.rb b/lib/file_browser/rails_tasks.rb
deleted file mode 100644
index 4811ad8..0000000
--- a/lib/file_browser/rails_tasks.rb
+++ /dev/null
@@ -1,7 +0,0 @@
-# Some glue to make it easy to include Rails-specific rake tasks in
-# your Rails application. Simply put the following at the bottom of
-# your Rakefile:
-#
-# require 'file_browser/rails_tasks'
-glob = File.join File.dirname(__FILE__), '../tasks/*.rake'
-Dir[glob].each {|ext| load ext}
\ No newline at end of file
diff --git a/lib/tasks/assets.rake b/lib/tasks/assets.rake
deleted file mode 100644
index 98c9237..0000000
--- a/lib/tasks/assets.rake
+++ /dev/null
@@ -1,45 +0,0 @@
-namespace :file_browser do
- namespace :assets do
-
- desc "Copy assets (i.e. public/) directory to main public/"
- task :copy => [:copy_javascripts, :copy_images, :copy_stylesheets]
-
- task :copy_javascripts do
- if file_browser_path('public/javascripts/').exist?
- src = file_browser_path('public/javascripts/').children
- dest = app_path 'public/javascripts/'
- FileUtils.cp_r src, dest
- end
- end
-
- task :copy_stylesheets do
- if file_browser_path('public/stylesheets/').exist?
- src = file_browser_path('public/stylesheets/').children
- dest = app_path 'public/stylesheets/'
- FileUtils.cp_r src, dest
- end
- end
-
- task :copy_images do
- if file_browser_path('public/images/').exist?
- src = file_browser_path('public/images/').children
- dest = app_path 'public/images/file_browser/'
- FileUtils.rm_rf dest.children
- FileUtils.cp_r src, dest
- end
- end
-
- private
-
- def file_browser_path(path)
- Pathname.new(__FILE__).realpath.dirname.join('../../').join path
- end
-
- def app_path(path)
- Pathname.getwd.realpath.join(path).tap do |p|
- p.mkpath
- end
- end
-
- end
-end
diff --git a/rails/init.rb b/rails/init.rb
deleted file mode 100644
index d5728d9..0000000
--- a/rails/init.rb
+++ /dev/null
@@ -1 +0,0 @@
-require 'file_browser'
diff --git a/test/functional/uploaded_files_controller_test.rb b/test/functional/uploaded_files_controller_test.rb
index 820300a..700c3d1 100644
--- a/test/functional/uploaded_files_controller_test.rb
+++ b/test/functional/uploaded_files_controller_test.rb
@@ -1,174 +1,179 @@
require 'test_helper'
class UploadedFilesControllerTest < ActionController::TestCase
test 'root directory' do
get :index, :path => [], :storage => 'local'
assert_response :success
assert_select 'h1', 'Root Directory'
assert_select 'a', :text => /Return to/, :count => 0
assert_select 'li', 4
assert_select 'a[href=?]', '/local/uploaded_files/index/dir1'
assert_select 'form[action=?]', '/local/uploaded_files/dir1'
assert_select 'a[href=?]', '/local/uploaded_files/index/empty'
assert_select 'form[action=?]', '/local/uploaded_files/empty'
assert_select 'a[href=?]', '/local/uploaded_files/file1.txt'
assert_select 'form[action=?]', '/local/uploaded_files/file1.txt'
assert_select 'a[href=?]', '/local/uploaded_files/file2.txt'
assert_select 'form[action=?]', '/local/uploaded_files/file2.txt'
end
test 'empty directory' do
get :index, :path => ['empty'], :storage => 'local'
assert_response :success
assert_select 'h1', 'empty'
assert_select 'a', /Return to Root Directory/
assert_select 'li', 0
end
test 'subdirectory' do
get :index, :path => ['dir1'], :storage => 'local'
assert_response :success
assert_select 'h1', 'dir1'
assert_select 'a', /Return to Root Directory/
assert_select 'li', 2
assert_select 'a[href=?]', '/local/uploaded_files/index/dir1/subdir'
assert_select 'form[action=?]', '/local/uploaded_files/dir1/subdir'
assert_select 'a[href=?]', '/local/uploaded_files/dir1/subfile1.txt'
assert_select 'form[action=?]', '/local/uploaded_files/dir1/subfile1.txt'
end
test 'sub of sub' do
get :index, :path => ['dir1', 'subdir'], :storage => 'local'
assert_response :success
assert_select 'h1', 'subdir'
assert_select 'a', /Return to dir1/
assert_select 'li', 0
end
test 'show (root directory)' do
get :show, :path => ['file1.txt'], :storage => 'local'
assert_response :success
assert_equal 'File 1', @response.body
end
test 'show (subdir)' do
get :show, :path => ['dir1', 'subfile1.txt'], :storage => 'local'
assert_response :success
assert_equal 'File in subdirectory.', @response.body
end
test 'show (404)' do
get :show, :path => ['foo.txt'], :storage => 'local'
assert_response :not_found
end
test 'create folder (root directory)' do
dest = storage_path.join 'foo'
FileUtils.rmdir dest if dest.exist?
assert !dest.exist?
@request.env["HTTP_REFERER"] = '/local/uploaded_files/index'
post :create, :path => [], :data => 'foo', :storage => 'local'
assert dest.directory?
FileUtils.rmdir dest if dest.exist?
end
test 'create folder (subdirectory)' do
dest = storage_path.join 'dir1/foo'
FileUtils.rmdir dest if dest.exist?
assert !dest.exist?
@request.env["HTTP_REFERER"] = '/local/uploaded_files/index/dir1'
post :create, :path => ['dir1'], :data => 'foo', :storage => 'local'
assert dest.directory?
FileUtils.rmdir dest if dest.exist?
end
test 'create file (root directory)' do
dest = storage_path.join 'foo.txt'
FileUtils.rm dest if dest.exist?
assert !dest.exist?
@request.env["HTTP_REFERER"] = '/local/uploaded_files/index'
file = StringIO.new('Test content')
def file.original_filename; 'foo.txt' end
post :create, :path => [], :data => file, :storage => 'local'
assert dest.exist?
FileUtils.rm dest if dest.exist?
end
test 'create file (subdirectory)' do
dest = storage_path.join 'dir1/foo.txt'
FileUtils.rm dest if dest.exist?
assert !dest.exist?
@request.env["HTTP_REFERER"] = '/local/uploaded_files/index/dir1'
file = StringIO.new('Test content')
def file.original_filename; 'foo.txt' end
post :create, :path => ['dir1'], :data => file, :storage => 'local'
assert dest.exist?
FileUtils.rm dest if dest.exist?
end
test 'remove file (root directory)' do
dest = storage_path.join 'foo.txt'
File.open(dest, 'w+') {|f| f << 'Remove me'}
assert dest.exist?
@request.env["HTTP_REFERER"] = '/local/uploaded_files/index'
delete :destroy, :path => ['foo.txt'], :storage => 'local'
assert !dest.exist?
end
test 'remove file (sub-directory)' do
dest = storage_path.join 'dir1/foo.txt'
File.open(dest, 'w+') {|f| f << 'Remove me'}
assert dest.exist?
@request.env["HTTP_REFERER"] = '/local/uploaded_files/index/dir1'
delete :destroy, :path => ['dir1', 'foo.txt'], :storage => 'local'
assert !dest.exist?
end
test 'remove directory (root directory)' do
dest = storage_path.join 'bar'
dest.mkpath
assert dest.directory?
@request.env["HTTP_REFERER"] = '/local/uploaded_files/index'
delete :destroy, :path => ['bar'], :storage => 'local'
assert !dest.exist?
end
test 'remove directory (sub-directory)' do
dest = storage_path.join 'dir1/bar'
dest.mkpath
assert dest.directory?
@request.env["HTTP_REFERER"] = '/local/uploaded_files/index/dir1'
delete :destroy, :path => ['dir1', 'bar'], :storage => 'local'
assert !dest.exist?
end
+ def setup
+ # Somehow this is getting cleared so reset it for testing
+ FileBrowser.storages[:local] = FilesystemStorage.new storage_path
+ end
+
private
def storage_path
Pathname.new(__FILE__).dirname.join '../fixtures/fs_storage'
end
-end
\ No newline at end of file
+end
diff --git a/test/test_app_template.rb b/test/test_app_template.rb
index 87596d1..4af8e0c 100644
--- a/test/test_app_template.rb
+++ b/test/test_app_template.rb
@@ -1,33 +1,20 @@
-lib 'test_gem_locator.rb', <<FILE
-class TestGemLocator < Rails::Plugin::Locator
- def plugins
- Rails::Plugin.new(File.join(File.dirname(__FILE__), *%w(.. .. ..)))
- end
-end
-FILE
-
-lib 'tasks/file_browser_tasks.rake', <<FILE
-require File.join(File.dirname(__FILE__), *%w(.. .. .. .. lib file_browser rails_tasks))
-FILE
-
environment <<CONFIG
-require 'test_gem_locator'
-config.plugin_locators << TestGemLocator
+ require File.join(File.dirname(__FILE__), *%w(.. .. .. lib file_browser.rb))
CONFIG
+gem 'ruby-debug'
+
initializer 'file_browser_config.rb', <<REGISTER
FileBrowser.storages[:local] =
FilesystemStorage.new Rails.root.join('../fixtures/fs_storage')
REGISTER
file 'public/javascripts/stub.js', <<JS
Event.observe(document, 'dom:loaded', function() {
Event.observe(document, 'file_browser:select', function(event) {
alert(event.memo+' selected');
});
});
JS
-
-rake 'file_browser:assets:copy'
diff --git a/test/test_helper.rb b/test/test_helper.rb
index 77a5d52..6301d24 100644
--- a/test/test_helper.rb
+++ b/test/test_helper.rb
@@ -1,11 +1,11 @@
ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/test_app/config/environment")
-require 'test_help'
+require 'rails/test_help'
$: << File.expand_path(File.dirname(__FILE__) + '/..')
require 'file_browser'
class ActiveSupport::TestCase
self.use_transactional_fixtures = true
self.use_instantiated_fixtures = false
-end
\ No newline at end of file
+end
diff --git a/test/unit/uploaded_file_test.rb b/test/unit/uploaded_file_test.rb
index 8097077..49c9637 100644
--- a/test/unit/uploaded_file_test.rb
+++ b/test/unit/uploaded_file_test.rb
@@ -1,26 +1,26 @@
require 'test_helper'
class UploadedFileTest < ActiveSupport::TestCase
test 'initialization and accessors' do
uf = UploadedFile.new('/bar/foo.txt', 'text/plain', '/uploaded_files/bar/foo.txt') {StringIO.new "Bar"}
assert_equal '/bar/foo.txt', uf.path
assert_equal '/uploaded_files/bar/foo.txt', uf.public_path
assert_equal 'Bar', uf.stream.read
assert_equal 'text/plain', uf.mime_type
assert_equal 'txt', uf.extension
assert_equal 'foo.txt', uf.to_s
end
test 'no extension' do
uf = UploadedFile.new 'foo'
assert_nil uf.extension
end
test 'general_type' do
assert_equal 'compressed', UploadedFile.new('test.fake', 'application/zip').general_type
assert_equal 'compressed', UploadedFile.new('test.zip', 'application/octet-stream').general_type
assert_equal 'unknown', UploadedFile.new('test.fake', 'application/fake').general_type
end
-end
\ No newline at end of file
+end
|
eric1234/file_browser
|
f53aadb421967e6cba4b3e39a7a13e73131fa93d
|
Bump version.
|
diff --git a/file_browser.gemspec b/file_browser.gemspec
index 15b5e86..50fdcee 100644
--- a/file_browser.gemspec
+++ b/file_browser.gemspec
@@ -1,20 +1,20 @@
Gem::Specification.new do |s|
s.name = 'file_browser'
- s.version = '0.0.1'
+ s.version = '0.0.2'
s.homepage = 'http://wiki.github.com/eric1234/file_browser/'
s.author = 'Eric Anderson'
s.email = 'eric@pixelwareinc.com'
s.add_dependency 'rails'
s.files = Dir['**/*'].reject do |f|
f =~ /^test/ || f == 'file_browser.gemspec' || f =~ /^pkg/
end
s.has_rdoc = true
s.extra_rdoc_files << 'README'
s.rdoc_options << '--main' << 'README'
s.summary = 'A Rails-gem for managing files'
s.description = <<-DESCRIPTION
Provides a web-based UI to manage a filesystem. Useful as an
alternative to FTP and also to integrate with products such
as CKEditor.
DESCRIPTION
-end
\ No newline at end of file
+end
|
eric1234/file_browser
|
f1019bcc30f6f7604c32fc5d78c47019bfe6dfb7
|
Support a "select_only" interface apps that want less power.
|
diff --git a/app/views/uploaded_files/index.html.erb b/app/views/uploaded_files/index.html.erb
index 718acb4..2b9544b 100644
--- a/app/views/uploaded_files/index.html.erb
+++ b/app/views/uploaded_files/index.html.erb
@@ -1,40 +1,42 @@
-<h1><%= @current_directory %></h1>
-
-<fieldset id="upload-forms">
- <legend>Add New Content</legend>
-
- <% uploaded_file_form_tag do %>
- <label for="file_data">Upload File</label>
- <%= file_field_tag :data, :id => 'file_data' %>
- <%= submit_tag 'Upload' %>
- <% end %>
+<% unless FileBrowser.select_only %>
+ <h1><%= @current_directory %></h1>
- <% uploaded_file_form_tag do %>
- <label for="directory_data">Create Directory</label>
- <%= text_field_tag :data, nil, :id => 'directory_data' %>
- <%= submit_tag 'Create' %>
- <% end %>
-</fieldset>
-
-<%= link_to_up "« Return to ?" %>
+ <fieldset id="upload-forms">
+ <legend>Add New Content</legend>
+
+ <% uploaded_file_form_tag do %>
+ <label for="file_data">Upload File</label>
+ <%= file_field_tag :data, :id => 'file_data' %>
+ <%= submit_tag 'Upload' %>
+ <% end %>
+
+ <% uploaded_file_form_tag do %>
+ <label for="directory_data">Create Directory</label>
+ <%= text_field_tag :data, nil, :id => 'directory_data' %>
+ <%= submit_tag 'Create' %>
+ <% end %>
+ </fieldset>
+
+ <%= link_to_up "« Return to ?" %>
+<% end %>
<ul id="directory-index" class="<%= 'clickable' if params[:integration] %>">
<% for directory in @directories %>
<li class="directory">
<%= image_tag "file_browser/folder.png", :alt => '' %>
<%= link_to_directory directory %>
<%= link_to_destroy directory %>
</li>
<% end %>
<% for file in @uploaded_files %>
<li class="file">
<%= image_tag "file_browser/#{file.general_type}.png", :alt => '' %>
<%= link_to_uploaded_file file %>
<%= link_to_destroy file.path %>
</li>
<% end %>
</ul>
<% content_for :file_browser_footer do %>
<%= javascript_include_tag params[:integration] %>
<% end if params[:integration] %>
diff --git a/lib/file_browser.rb b/lib/file_browser.rb
index 38fba99..65ba6f5 100644
--- a/lib/file_browser.rb
+++ b/lib/file_browser.rb
@@ -1,18 +1,26 @@
module FileBrowser
# Stores all configured storages for the current app. The application
# should configure this similar to:
#
# FileBrowser.storages[:local] = FilesystemStorage.new('/path/to/root')
#
# When the browser is loaded it will have the key as the prefix. So
# for example:
#
# /local/uploaded_files
#
# Will pull the UploadedFilesController::index action using the :local
# key set above.
mattr_accessor :storages
self.storages = {}
-end
\ No newline at end of file
+ # If set to true then the file browser provides no way to create
+ # directories or add files. So you can only select files. You can
+ # still add files via the drop functionality. This is not a security
+ # issue but just simplifying the interface so the file browser is
+ # as simple as possible.
+ mattr_accessor :select_only
+ self.select_only = false
+
+end
|
eric1234/file_browser
|
c0c8862e11b4ce27e7b73b8d75980c6ebc3247f9
|
Select file to choose instead of select then button.
|
diff --git a/app/views/uploaded_files/index.html.erb b/app/views/uploaded_files/index.html.erb
index 9541aa5..718acb4 100644
--- a/app/views/uploaded_files/index.html.erb
+++ b/app/views/uploaded_files/index.html.erb
@@ -1,47 +1,40 @@
<h1><%= @current_directory %></h1>
<fieldset id="upload-forms">
<legend>Add New Content</legend>
<% uploaded_file_form_tag do %>
<label for="file_data">Upload File</label>
<%= file_field_tag :data, :id => 'file_data' %>
<%= submit_tag 'Upload' %>
<% end %>
<% uploaded_file_form_tag do %>
<label for="directory_data">Create Directory</label>
<%= text_field_tag :data, nil, :id => 'directory_data' %>
<%= submit_tag 'Create' %>
<% end %>
</fieldset>
<%= link_to_up "« Return to ?" %>
-<ul id="directory-index">
+<ul id="directory-index" class="<%= 'clickable' if params[:integration] %>">
<% for directory in @directories %>
- <li>
+ <li class="directory">
<%= image_tag "file_browser/folder.png", :alt => '' %>
<%= link_to_directory directory %>
<%= link_to_destroy directory %>
</li>
<% end %>
<% for file in @uploaded_files %>
- <li>
+ <li class="file">
<%= image_tag "file_browser/#{file.general_type}.png", :alt => '' %>
- <%= file %>
- <%= link_to_uploaded_file file, "Download" %>
+ <%= link_to_uploaded_file file %>
<%= link_to_destroy file.path %>
</li>
<% end %>
</ul>
-<% if params[:integration] %>
- <% content_for :file_browser_footer do %>
- <%= javascript_include_tag params[:integration] %>
- <% end %>
- <div id="file-browser-actions">
- <%= submit_tag 'Choose File', :type => 'button', :id => 'select-file-trigger' %>
- <%= link_to 'Cancel', '#', :id => 'cancel-file-select' %>
- </div>
-<% end %>
\ No newline at end of file
+<% content_for :file_browser_footer do %>
+ <%= javascript_include_tag params[:integration] %>
+<% end if params[:integration] %>
diff --git a/example_integrations/ck_browser.js b/example_integrations/ck_browser.js
index b254991..9fd15dc 100644
--- a/example_integrations/ck_browser.js
+++ b/example_integrations/ck_browser.js
@@ -1,21 +1,17 @@
/* Put this in your javascripts directory. Then configure CKEditor with
* the following attributes:
*
* filebrowserBrowseUrl: '/local/uploaded_files/select/ck_browser',
* filebrowserUploadUrl: '/local/uploaded_files/drop/ck_browser',
*
* (This assumes your storage is named "local")
*/
Event.observe(document, 'dom:loaded', function() {
Event.observe(document, 'file_browser:select', function(event) {
params = window.location.search.toQueryParams();
(window.opener || window.parent).CKEDITOR.tools.callFunction(params['CKEditorFuncNum'], event.memo);
window.close();
});
- Event.observe(document, 'file_browser:cancel', function() {
- window.close();
- });
-
-});
\ No newline at end of file
+});
diff --git a/public/javascripts/file_browser.js b/public/javascripts/file_browser.js
index 74cc56d..b770a7d 100644
--- a/public/javascripts/file_browser.js
+++ b/public/javascripts/file_browser.js
@@ -1,34 +1,13 @@
Event.observe(document, 'dom:loaded', function() {
- var items = $$('#directory-index li')
+ var items = $$('#directory-index.clickable li.file');
items.each(function(e) {
e.observe('click', function() {
- items.each(function(i) {i.removeClassName('selected')});
- e.addClassName('selected');
+ if(event.element().getAttribute('value') == 'X') return;
+ event.stop();
+ var target = event.element().up('li').down('a');
+ document.fire('file_browser:select', target.getAttribute('href'));
})
});
- var trigger = $('select-file-trigger');
- if(trigger)
- trigger.observe('click', function(event) {
- event.stop();
- var selected = items.find(function(e) {return e.hasClassName('selected')});
- if(!selected) {
- alert('No file selected');
- return;
- }
- var target = selected.down('a');
- if(target.innerHTML == 'Download') {
- document.fire('file_browser:select', target.getAttribute('href'));
- } else {
- alert('You must select a file, not a directory');
- }
- });
-
- var cancel = $('cancel-file-select');
- if(cancel)
- cancel.observe('click', function(event) {
- event.stop();
- document.fire('file_browser:cancel');
- });
-});
\ No newline at end of file
+});
diff --git a/public/stylesheets/file_browser.css b/public/stylesheets/file_browser.css
index 2e7f06b..a9750cf 100644
--- a/public/stylesheets/file_browser.css
+++ b/public/stylesheets/file_browser.css
@@ -1,26 +1,24 @@
#upload-forms {width: 32em; padding: 1em}
#upload-forms label {float: left; width: 10em; font-weight: bold}
#upload-forms input[type=text], #upload-forms input[type=file] {width: 20em}
#directory-index, #directory-index li {margin: 0; padding: 0; list-style-type: none}
#directory-index {margin: 1em 0}
#directory-index li {
float: left;
height: 175px;
width: 150px;
border: thin solid gray;
background-color: #E8E8E8;
text-align: center;
margin: 0.5em 1em;
position: relative;
}
-#directory-index li.selected {background-color: #D2D2D2}
#directory-index form {
position: absolute;
top: 0; right: 0;
display: none
}
#directory-index li:hover {visibility: visible} /* IE hack to enable :hover */
#directory-index li:hover form {display: block}
#directory-index a {color: black; display: block}
#up-dir {margin: 1em; display: block}
-#file-browser-actions {clear: both}
diff --git a/test/test_app_template.rb b/test/test_app_template.rb
index 31b30da..87596d1 100644
--- a/test/test_app_template.rb
+++ b/test/test_app_template.rb
@@ -1,37 +1,33 @@
lib 'test_gem_locator.rb', <<FILE
class TestGemLocator < Rails::Plugin::Locator
def plugins
Rails::Plugin.new(File.join(File.dirname(__FILE__), *%w(.. .. ..)))
end
end
FILE
lib 'tasks/file_browser_tasks.rake', <<FILE
require File.join(File.dirname(__FILE__), *%w(.. .. .. .. lib file_browser rails_tasks))
FILE
environment <<CONFIG
require 'test_gem_locator'
config.plugin_locators << TestGemLocator
CONFIG
initializer 'file_browser_config.rb', <<REGISTER
FileBrowser.storages[:local] =
FilesystemStorage.new Rails.root.join('../fixtures/fs_storage')
REGISTER
file 'public/javascripts/stub.js', <<JS
Event.observe(document, 'dom:loaded', function() {
Event.observe(document, 'file_browser:select', function(event) {
alert(event.memo+' selected');
});
- Event.observe(document, 'file_browser:cancel', function() {
- alert('Selection canceled');
- });
-
});
JS
-rake 'file_browser:assets:copy'
\ No newline at end of file
+rake 'file_browser:assets:copy'
|
eric1234/file_browser
|
133dd24ddc04d9da534ee56c73e794a9254a0380
|
Getting closer to 3.0
|
diff --git a/Rakefile b/Rakefile
index b654710..eab3c02 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,28 +1,28 @@
require 'fileutils'
require 'rake/testtask'
require 'rake/gempackagetask'
desc 'Prepare testing by creating test app'
task :test_app do
- sh "rails -q -m test/test_app_template.rb test/test_app" unless
+ sh "rails _2.3.9_ -q -m test/test_app_template.rb test/test_app" unless
File.exists? 'test/test_app'
end
spec = eval File.read('file_browser.gemspec')
Rake::GemPackageTask.new spec do |pkg|
pkg.need_tar = false
end
desc "Publish gem to rubygems.org"
task :publish => :package do
`gem push pkg/#{spec.name}-#{spec.version}.gem`
end
Rake::TestTask.new(:test => :test_app) do |task|
task.libs << "lib"
task.libs << "test"
task.pattern = "test/*/*_test.rb"
task.verbose = false
end
-task :default => :test
\ No newline at end of file
+task :default => :test
diff --git a/lib/tasks/assets.rake b/lib/tasks/assets.rake
index 5085566..98c9237 100644
--- a/lib/tasks/assets.rake
+++ b/lib/tasks/assets.rake
@@ -1,45 +1,45 @@
namespace :file_browser do
namespace :assets do
desc "Copy assets (i.e. public/) directory to main public/"
task :copy => [:copy_javascripts, :copy_images, :copy_stylesheets]
task :copy_javascripts do
if file_browser_path('public/javascripts/').exist?
src = file_browser_path('public/javascripts/').children
dest = app_path 'public/javascripts/'
FileUtils.cp_r src, dest
end
end
task :copy_stylesheets do
if file_browser_path('public/stylesheets/').exist?
src = file_browser_path('public/stylesheets/').children
dest = app_path 'public/stylesheets/'
FileUtils.cp_r src, dest
end
end
task :copy_images do
if file_browser_path('public/images/').exist?
src = file_browser_path('public/images/').children
dest = app_path 'public/images/file_browser/'
FileUtils.rm_rf dest.children
FileUtils.cp_r src, dest
end
end
private
def file_browser_path(path)
Pathname.new(__FILE__).realpath.dirname.join('../../').join path
end
def app_path(path)
- returning(Pathname.getwd.realpath.join(path)) do |p|
+ Pathname.getwd.realpath.join(path).tap do |p|
p.mkpath
end
end
end
-end
\ No newline at end of file
+end
|
eric1234/file_browser
|
c2757fe57b05f7b543d426f37e3f6579960a7187
|
Credit where credit is due
|
diff --git a/README b/README
index a2fbb6b..e3d1929 100644
--- a/README
+++ b/README
@@ -1,62 +1,63 @@
-DESCRIPTION
------------
+= DESCRIPTION
A rails plugin that provides a basic file browser. The primary use
case for this plugin is:
* To manage a directory of files includes subdirectories
* To integration with products like CKEditor for selecting files.
Guiding Principals:
* No database required
* Multiple backends (filesystem, S3, etc.) - Filesystem only currently
* Pluggable integration with 3rd party products such as CKEditor
Possible Future Features:
* Launcher can specify only certain file types to show
(images only, only certain extensions, etc.)
* Allow basic image manipulation (resize, crop, etc.)
* File upload progress monitoring (for large files)
-SETUP
------
+= SETUP
In your environment.rb add:
config.gem 'file_browser'
In an initializer add:
FileBrowser.storages[:local] =
FilesystemStorage.new Rails.root.join('public/uploaded_files')
Change the above path to be wherever you want to write files. Also make
sure that directory is writable by the application.
Next run `rake file_browser:assets:copy` to copy the necessary
javascript, CSS and images to your public directory. You can feel free
to update those files. The copy only happens when you run the rake task.
Note that you need to put `require 'file_browser/rails_tasks'` in your
Rakefile for the rake tasks to be included in your app.
Finally point your browser to /local/uploaded_files/index and start
managing your files via the web.
See example_integrations directory for how to integrate with 3rd party
tools such as CKEditor.
-CONFIGURATION
--------------
+= CONFIGURATION
By default the app will use the "file_browser" layout. Obviously your
can override that in your application if you want. If you want it to
use the same layout as your main layout simply symlink
file_browser.html.erb to your application.html.erb file. If you use
your own layout make sure that it includes the prototype library and
that it yields to the symbol :file_browser_footer.
You can have multiple storage repositories that can be registered and
accessed. See FileBrowser#storages for more info.
+= CREDIT
+
+This gem was developed by Eric Anderson (http://pixelwareinc.com) while
+developing projects under Red Tusk Studios (http://redtusk.com).
|
eric1234/file_browser
|
08b476b01715afaaeaab6496cc5609ed3796301e
|
Allow publishing of gem.
|
diff --git a/Rakefile b/Rakefile
index b6b1f19..b654710 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,23 +1,28 @@
require 'fileutils'
require 'rake/testtask'
require 'rake/gempackagetask'
desc 'Prepare testing by creating test app'
task :test_app do
sh "rails -q -m test/test_app_template.rb test/test_app" unless
File.exists? 'test/test_app'
end
spec = eval File.read('file_browser.gemspec')
Rake::GemPackageTask.new spec do |pkg|
pkg.need_tar = false
end
+desc "Publish gem to rubygems.org"
+task :publish => :package do
+ `gem push pkg/#{spec.name}-#{spec.version}.gem`
+end
+
Rake::TestTask.new(:test => :test_app) do |task|
task.libs << "lib"
task.libs << "test"
task.pattern = "test/*/*_test.rb"
task.verbose = false
end
task :default => :test
\ No newline at end of file
|
eric1234/file_browser
|
647ac95e980aa81e5e1dcab7564727f45909824d
|
Firefox style happyness.
|
diff --git a/public/stylesheets/file_browser.css b/public/stylesheets/file_browser.css
index 48aaaa0..2e7f06b 100644
--- a/public/stylesheets/file_browser.css
+++ b/public/stylesheets/file_browser.css
@@ -1,26 +1,26 @@
-#upload-forms {width: 25em; padding: 1em}
-#upload-forms label {float: left; width: 8em; font-weight: bold}
-#upload-forms input[type=text], #upload-forms input[type=file] {width: 15em}
+#upload-forms {width: 32em; padding: 1em}
+#upload-forms label {float: left; width: 10em; font-weight: bold}
+#upload-forms input[type=text], #upload-forms input[type=file] {width: 20em}
#directory-index, #directory-index li {margin: 0; padding: 0; list-style-type: none}
#directory-index {margin: 1em 0}
#directory-index li {
float: left;
height: 175px;
width: 150px;
border: thin solid gray;
background-color: #E8E8E8;
text-align: center;
margin: 0.5em 1em;
position: relative;
}
#directory-index li.selected {background-color: #D2D2D2}
#directory-index form {
position: absolute;
top: 0; right: 0;
display: none
}
#directory-index li:hover {visibility: visible} /* IE hack to enable :hover */
#directory-index li:hover form {display: block}
#directory-index a {color: black; display: block}
#up-dir {margin: 1em; display: block}
-#file-browser-actions {clear: both}
\ No newline at end of file
+#file-browser-actions {clear: both}
|
higepon/spon
|
5a9e071aa2ed3ad8f3c378df06ed1a8bd5409a69
|
move file-copy, make-directory, and make-symbolic-link from (spon compat) to (spon tools).
|
diff --git a/compat.ikarus.sls b/compat.ikarus.sls
index a3539d1..84a03b8 100644
--- a/compat.ikarus.sls
+++ b/compat.ikarus.sls
@@ -1,46 +1,32 @@
(library (spon compat)
(export implementation-name
command
- file-copy
- make-directory
- make-symbolic-link
current-directory
)
(import (rnrs)
(spon config)
(only (ikarus) current-directory)
(ikarus ipc))
(define (implementation-name) "ikarus")
(define (command cmd . args)
(let-values (([pid p-stdin p-stdout p-stderr] (apply process cmd args)))
(zero? ; for now
(wstatus-exit-status
(cond ((quiet?)
(waitpid pid))
(else
(let ((p-message (transcoded-port p-stdout (native-transcoder)))
(p-error (transcoded-port p-stderr (native-transcoder))))
(let loop ((status #f))
(when (verbose?)
(let ((message (get-string-all p-message)))
(unless (eof-object? message)
(display message)
(put-string (current-output-port) message))))
(let ((err (get-string-all p-error)))
(unless (eof-object? err)
(put-string (current-error-port) err)))
(or status (loop (waitpid pid #f)))))))))))
-
- ;; copied from compat.ypsilon.sls for now.
- ;; must be refactor.
- (define (file-copy src dst mode)
- (command "install" "-m" (number->string mode 8) src dst))
-
- (define (make-directory dir mode)
- (command "install" "-m" (number->string mode 8) "-d" dir))
-
- (define (make-symbolic-link target link)
- (command "ln" "-sf" target link))
)
diff --git a/compat.mosh.sls b/compat.mosh.sls
index 4f0956e..81ebea5 100644
--- a/compat.mosh.sls
+++ b/compat.mosh.sls
@@ -1,49 +1,37 @@
(library (spon compat)
(export implementation-name
command
- file-copy
- make-directory
- make-symbolic-link
current-directory
)
(import (rnrs)
(srfi :39)
(prefix (only (mosh) current-directory set-current-directory!) mosh:)
(only (mosh process) spawn waitpid pipe)
(spon config))
(define (implementation-name) "mosh")
;; todo replace with custom port
(define (spawn2->null command args)
(let-values ([(in out) (pipe)])
(let-values ([(pid cin cout cerr) (spawn command args (list #f out out))])
(close-port out)
(close-port in)
(waitpid pid))))
(define (command cmd . args)
(cond
[(verbose?)
(let*-values ([(pid . _) (spawn cmd args '(#f #f #f))]
[(pid status) (waitpid pid)])
(zero? status))]
[else
(let-values ([(pid status) (spawn2->null cmd args)])
(zero? status))]))
- (define (file-copy src dst mode)
- (command "install" "-m" (number->string mode 8) src dst))
-
- (define (make-directory dir mode)
- (command "install" "-m" (number->string mode 8) "-d" dir))
-
- (define (make-symbolic-link target link)
- (command "ln" "-sf" target link))
-
(define current-directory
(make-parameter (mosh:current-directory)
(lambda (val)
(mosh:set-current-directory! val)
val)))
)
diff --git a/compat.sls b/compat.sls
index 59d524a..9109e05 100644
--- a/compat.sls
+++ b/compat.sls
@@ -1,33 +1,30 @@
(library (spon compat)
(export implementation-name
command
- file-copy
- make-directory
- make-symbolic-link
current-directory
)
(import (rnrs)
(spon config))
(define (implementation-name) "scheme")
;; -- command :: (String, [String]) -> Boolean
;; Execute an external command `cmd' with arguments `args'.
;; If the command is successfully exited, returns #t,
;; otherwise returns #f.
;; When `verbose?' procedure (in the library (spon config)) returns #f,
;; standard output of the command is discarded.
;; When `silent?' procedure (also in the same library) returns #f,
;; standard error of the command is discarded.
(define (command cmd . args)
(raise (condition
(make-implementation-restriction-violation)
(make-who-condition 'command)
(make-message-condition
(string-append
"Compatibility layer is not implemented. "
(string-titlecase system-name)
" seems to be not supported by your implementation. "
"Please consult the author of your implementation."))
(make-irritants-condition (cons cmd args)))))
)
diff --git a/compat.ypsilon.sls b/compat.ypsilon.sls
index 67ea2b2..77caa1a 100644
--- a/compat.ypsilon.sls
+++ b/compat.ypsilon.sls
@@ -1,47 +1,37 @@
(library (spon compat)
(export implementation-name
command
file-copy
make-directory
make-symbolic-link
current-directory
)
(import (rnrs)
(only (core)
current-directory
destructuring-bind
process
process-wait)
(spon config))
(define (implementation-name) "ypsilon")
(define (command cmd . args)
(destructuring-bind (pid p-stdin p-stdout p-stderr)
(apply process cmd args)
(zero?
(cond ((quiet?)
(process-wait pid #f)) ; nohang = #t
((verbose?)
(let ((p-message (transcoded-port p-stdout (native-transcoder)))
(p-error (transcoded-port p-stderr (native-transcoder))))
(let loop ((status #f))
(when (verbose?)
(let ((message (get-string-all p-message)))
(unless (eof-object? message)
(put-string (current-output-port) message))))
(let ((error (get-string-all p-error)))
(unless (eof-object? error)
(put-string (current-error-port) error)))
(or status (loop (process-wait pid #t)))))))))) ; nohang = #f
-
- (define (file-copy src dst mode)
- (command "install" "-m" (number->string mode 8) src dst))
-
- (define (make-directory dir mode)
- (command "install" "-m" (number->string mode 8) "-d" dir))
-
- (define (make-symbolic-link target link)
- (command "ln" "-sf" target link))
-
) ;[end]
diff --git a/tools.sls b/tools.sls
index a4a0fbb..e472820 100644
--- a/tools.sls
+++ b/tools.sls
@@ -1,331 +1,340 @@
(library (spon tools)
(export download verify decompress initialize setup install
system-name verbose? quiet? download-error? download-error-uri
implementation-name command
file-copy make-directory make-symbolic-link
current-directory)
(import (rnrs)
(srfi :39)
(srfi :48)
(spon config)
(spon compat))
(define-condition-type &spon &error
make-spon-error spon-error?)
(define-condition-type &download &spon
make-download-error download-error?
(uri download-error-uri))
(define-record-type (version make-version version?)
(fields
(immutable v1 version-major)
(immutable v2 version-minor)
(immutable v3 version-patch)))
(define-record-type (pkg-stat make-pkg-stat pkg-stat?)
(fields
(immutable status pkg-stat-status)
(immutable version pkg-stat-version)))
(define-record-type (pkg-info make-pkg-info pkg-info?)
(fields
(immutable name pkg-info-name)
(immutable version pkg-info-version)
(immutable depends pkg-info-depends)
(immutable description pkg-info-description)
(mutable status pkg-info-status pkg-info-status-set!)))
+ (define (file-copy src dst mode)
+ (command "install" "-m" (number->string mode 8) src dst))
+
+ (define (make-directory dir mode)
+ (command "install" "-m" (number->string mode 8) "-d" dir))
+
+ (define (make-symbolic-link target link)
+ (command "ln" "-sf" target link))
+
(define-syntax do-procs
(syntax-rules ()
((_ (pre cmd ok ng) ...)
(and (begin
(unless (quiet?)
(format #t "----> ~A~%" pre))
(let ((res cmd))
(unless (quiet?)
(if res
(when ok
(format #t "----> ~A~%" ok))
(format #t "----> ERROR: ~A~%" ng)))
res))
...))))
(define (read-package-list)
(define (get-version alis)
(cond ((assq 'version alis)
=> (lambda (xs)
(and (= (length (cdr xs)) 3)
(for-all number? (cdr xs))
(apply make-version (cdr xs)))))
(else #f)))
(let ((ht (make-eq-hashtable)))
(let ((file (format #f "~A/~A" base-path "package-list.sds")))
(when (file-exists? file)
(call-with-input-file file
(lambda (in)
(do ((i (read in) (read in)))
((eof-object? i))
(let ((name (car i))
(version (get-version (cdr i)))
(depends (cond ((assq 'depends (cdr i)) => cdr)
(else #f)))
(description (let ((d (assq 'description (cdr i))))
(and d (apply string-append (cdr d)))))
(status #f))
(hashtable-set! ht name
(make-pkg-info name version depends description status))))))))
(let ((file (format #f "~A/~A" base-path "install.sds")))
(when (file-exists? file)
(call-with-input-file file
(lambda (in)
(do ((i (read in) (read in)))
((eof-object? i))
(let ((name (car i))
(status (and (cadr i) #t))
(version (get-version (cddr i))))
(if (hashtable-contains? ht name)
(let ((p (hashtable-ref ht name)))
(pkg-info-status-set! p
(make-pkg-stat status version))
(hashtable-set! ht name p))
(hashtable-set! ht name
(make-pkg-info name #f #f #f
(make-pkg-stat status version))))))))))
ht))
(define (write-install-status pkg-ht)
(let ((file (format #f "~A/~A" base-path "install.sds")))
(call-with-output-file file
(lambda (out)
(let-values (((ks vs) (hashtable-entries pkg-ht)))
(vector-for-each
(lambda (key val)
(let ((stat (pkg-info-status val)))
(when (pkg-stat? stat)
(write (cons*
key (pkg-stat-status stat)
(if (version? (pkg-stat-version stat))
(list (version->list (pkg-stat-version stat)))
'()))
out)
(newline out))))
ks vs))))))
(define (version<? v1 v2)
(cond ((< (version-major v1) (version-major v2)) #t)
((> (version-major v1) (version-major v2)) #f)
(else
(cond ((< (version-minor v1) (version-minor v2)) #t)
((> (version-minor v1) (version-minor v2)) #f)
(else
(cond ((< (version-patch v1) (version-patch v2)) #t)
(else #f)))))))
(define (version->string version)
(string-append (number->string (version-major version))
"." (number->string (version-minor version))
"." (number->string (version-patch version))))
(define (version->list version)
(list 'version
(version-major version)
(version-minor version)
(version-patch version)))
(define (package->symbol p)
(cond
((symbol? p) p)
((string? p) (string->symbol p))
((pkg-info? p) (pkg-info-name p))
(else #f)))
(define (package->string p)
(cond
((symbol? p) (symbol->string p))
((string? p) p)
((pkg-info? p)
(if (version? (pkg-info-version p))
(string-append (symbol->string (pkg-info-name p))
"-"
(version->string (pkg-info-version p)))
(symbol->string (pkg-info-name p))))
(else #f)))
(define (package-installed? p ht)
(cond
((pkg-info? p)
(let ((stat (pkg-info-status p)))
(if (pkg-stat? stat) (pkg-stat-status stat) stat)))
((symbol? p) (package-installed? (hashtable-ref ht p #f) ht))
((string? p) (package-installed? (string->symbol p) ht))
(else #f)))
(define (cmd-wget uri dir)
(or (apply command
((get-config) "wget")
"-N" "-P" dir uri (if (quiet?) '("-q") '()))
(raise (make-download-error uri))))
(define (cmd-gpg signature file)
(let ((gpg ((get-config) "gpg" #f)))
(or (not gpg)
(apply command
gpg
`(,@(if (quiet?) '("-q") '()) "--verify" signature file)))))
(define (cmd-tar file dir)
(apply command
((get-config) "tar")
"-xzf" file "-C" dir (if (quiet?) '() '("-v"))))
(define (download package)
(let* ((config (get-config))
(download-uri (config "download-uri" download-uri))
(pkg-uri (format "~A/~A.tar.gz" download-uri (package->string package)))
(sig-uri (format "~A.asc" pkg-uri))
(src-path (config "source-path" source-path)))
(do-procs
((format "Downloading package: ~A ..." pkg-uri)
(cmd-wget pkg-uri src-path)
#f
"Failed to download the package")
((format "Downloading signature: ~A ..." sig-uri)
(cmd-wget sig-uri src-path)
#f
"Failed to download the signature"))))
(define (verify package)
(let* ((config (get-config))
(src-path (config "source-path" source-path))
(pkg-file (format "~A/~A.tar.gz" src-path (package->string package)))
(sig-file (format "~A.asc" pkg-file)))
(or (not (config "gpg" #f))
(do-procs
("Veryfying package ..."
(cmd-gpg sig-file pkg-file)
#f
"cannot verify package.")))))
(define (decompress package)
(let* ((config (get-config))
(src-path (config "source-path" source-path))
(pkg-file (format "~A/~A.tar.gz" src-path (package->string package))))
(do-procs
("Decompressing package ..."
(cmd-tar pkg-file src-path)
#f
"error in decompressing package"))))
(define (initialize package mode)
(let* ((config (get-config))
(impl (implementation-name))
(src-path (config "source-path" source-path))
(pkg-path (format "~A/~A" source-path (package->string package)))
(install.ss (format "~A/install.ss" pkg-path)))
(do-procs
((format "Setup package for ~A ..." (string-upcase system-name))
(parameterize ((current-directory pkg-path))
(command impl install.ss (symbol->string mode)))
#f
(format "error in ~A" install.ss)))))
(define (setup package mode)
(let* ((config (get-config))
(impl (implementation-name))
(src-path (config "source-path" source-path))
(pkg-path (format "~A/~A" source-path (package->string package)))
(setup.ss (format "~A/setup.ss" pkg-path))
(setup.impl.ss (format "~A/setup.~A.ss" pkg-path impl)))
(do-procs
((format "Setup package to ~A ..." impl)
(parameterize ((current-directory pkg-path))
(command impl
(if (file-exists? setup.impl.ss) setup.impl.ss setup.ss)
(symbol->string mode)))
#f
(format "error in ~A" setup.ss)))))
(define (install package)
(define (install-rec package pkg-ht)
(let ((pi (hashtable-ref pkg-ht (package->symbol package) #f)))
(and (not (package-installed? pi pkg-ht))
(begin
(when (pkg-info? pi)
(let ((depends (pkg-info-depends pi)))
(when depends
(for-each (lambda (dep)
(install-rec dep pkg-ht))
depends))))
(let* ((p (if (pkg-info? pi) pi package))
(package-name (package->string p)))
(let ((r (do-procs
((format "Installing ~A" package-name)
(and (download p)
(verify p)
(decompress p)
(initialize p 'install)
(setup p 'install))
(format "~A is successfully installed.~%" package-name)
(format "~A install failed.~%" package-name)))))
(when r
(if (pkg-info? pi)
(pkg-info-status-set! pi (make-pkg-stat #t (pkg-info-version pi)))
(hashtable-set! pkg-ht
(package->symbol package)
(make-pkg-info package #f #f #f (make-pkg-stat #t #f)))))
r))))))
(let ((pkg-ht (read-package-list)))
(if (package-installed? package pkg-ht)
(begin
(format #t "----> ~A is already installed.~%" (package->string package))
#f)
(let ((r (install-rec package pkg-ht)))
(write-install-status pkg-ht)
r))))
(define (update package)
(define (updatable? pi)
(and (pkg-info? pi)
(let ((stat (pkg-info-status pi)))
(and (pkg-stat? stat)
(version<? (pkg-stat-version stat) (pkg-info-version pi))))))
(define (update-rec package pkg-ht)
(let* ((pi (hashtable-ref pkg-ht (package->symbol package) #f))
(package-name (package->string pi)))
(and (updatable? pi)
(begin
(let ((depends (pkg-info-depends pi)))
(when depends
(for-each (lambda (dep)
(update-rec dep pkg-ht))
depends)))
(let ((r (do-procs
((format "Updating ~A ..." package-name)
(and (download pi)
(verify pi)
(decompress pi)
(initialize pi 'update)
(setup pi 'update))
(format "~A is successfully update.~%" package-name)
(format "~A update failed.~%" package-name)))))
(when r
(if (pkg-info? pi)
(pkg-info-status-set! pi (make-pkg-stat #t (pkg-info-version pi)))
(hashtable-set! pkg-ht
(package->symbol package)
(make-pkg-info package #f #f #f (make-pkg-stat #t #f)))))
r)))))
(let ((pkg-ht (read-package-list)))
(let ((pi (hashtable-ref pkg-ht (package->symbol package) #f)))
(if (updatable? pi)
(let ((r (update-rec package pkg-ht)))
(write-install-status pkg-ht)
r)
(begin
(format #t "----> ~A can't update." (package->string package))
#f)))))
(define (uninstall package)
#f)
)
|
higepon/spon
|
5ee6e62bdf653a5a475c02c2fec0ae42e6d8f3e1
|
rename current-implementation-name to implementation-name.
|
diff --git a/compat.ikarus.sls b/compat.ikarus.sls
index 50bfa24..a3539d1 100644
--- a/compat.ikarus.sls
+++ b/compat.ikarus.sls
@@ -1,46 +1,46 @@
(library (spon compat)
- (export current-implementation-name
+ (export implementation-name
command
file-copy
make-directory
make-symbolic-link
current-directory
)
(import (rnrs)
(spon config)
(only (ikarus) current-directory)
(ikarus ipc))
- (define (current-implementation-name) "ikarus")
+ (define (implementation-name) "ikarus")
(define (command cmd . args)
(let-values (([pid p-stdin p-stdout p-stderr] (apply process cmd args)))
(zero? ; for now
(wstatus-exit-status
(cond ((quiet?)
(waitpid pid))
(else
(let ((p-message (transcoded-port p-stdout (native-transcoder)))
(p-error (transcoded-port p-stderr (native-transcoder))))
(let loop ((status #f))
(when (verbose?)
(let ((message (get-string-all p-message)))
(unless (eof-object? message)
(display message)
(put-string (current-output-port) message))))
(let ((err (get-string-all p-error)))
(unless (eof-object? err)
(put-string (current-error-port) err)))
(or status (loop (waitpid pid #f)))))))))))
;; copied from compat.ypsilon.sls for now.
;; must be refactor.
(define (file-copy src dst mode)
(command "install" "-m" (number->string mode 8) src dst))
(define (make-directory dir mode)
(command "install" "-m" (number->string mode 8) "-d" dir))
(define (make-symbolic-link target link)
(command "ln" "-sf" target link))
)
diff --git a/compat.mosh.sls b/compat.mosh.sls
index 51b50b7..4f0956e 100644
--- a/compat.mosh.sls
+++ b/compat.mosh.sls
@@ -1,49 +1,49 @@
(library (spon compat)
- (export current-implementation-name
+ (export implementation-name
command
file-copy
make-directory
make-symbolic-link
current-directory
)
(import (rnrs)
(srfi :39)
(prefix (only (mosh) current-directory set-current-directory!) mosh:)
(only (mosh process) spawn waitpid pipe)
(spon config))
- (define (current-implementation-name) "mosh")
+ (define (implementation-name) "mosh")
;; todo replace with custom port
(define (spawn2->null command args)
(let-values ([(in out) (pipe)])
(let-values ([(pid cin cout cerr) (spawn command args (list #f out out))])
(close-port out)
(close-port in)
(waitpid pid))))
(define (command cmd . args)
(cond
[(verbose?)
(let*-values ([(pid . _) (spawn cmd args '(#f #f #f))]
[(pid status) (waitpid pid)])
(zero? status))]
[else
(let-values ([(pid status) (spawn2->null cmd args)])
(zero? status))]))
(define (file-copy src dst mode)
(command "install" "-m" (number->string mode 8) src dst))
(define (make-directory dir mode)
(command "install" "-m" (number->string mode 8) "-d" dir))
(define (make-symbolic-link target link)
(command "ln" "-sf" target link))
(define current-directory
(make-parameter (mosh:current-directory)
(lambda (val)
(mosh:set-current-directory! val)
val)))
)
diff --git a/compat.sls b/compat.sls
index 91e2148..59d524a 100644
--- a/compat.sls
+++ b/compat.sls
@@ -1,33 +1,33 @@
(library (spon compat)
- (export current-implementation-name
+ (export implementation-name
command
file-copy
make-directory
make-symbolic-link
current-directory
)
(import (rnrs)
(spon config))
- (define (current-implementation-name) "scheme")
+ (define (implementation-name) "scheme")
;; -- command :: (String, [String]) -> Boolean
;; Execute an external command `cmd' with arguments `args'.
;; If the command is successfully exited, returns #t,
;; otherwise returns #f.
;; When `verbose?' procedure (in the library (spon config)) returns #f,
;; standard output of the command is discarded.
;; When `silent?' procedure (also in the same library) returns #f,
;; standard error of the command is discarded.
(define (command cmd . args)
(raise (condition
(make-implementation-restriction-violation)
(make-who-condition 'command)
(make-message-condition
(string-append
"Compatibility layer is not implemented. "
(string-titlecase system-name)
" seems to be not supported by your implementation. "
"Please consult the author of your implementation."))
(make-irritants-condition (cons cmd args)))))
)
diff --git a/compat.ypsilon.sls b/compat.ypsilon.sls
index 0b3feb1..67ea2b2 100644
--- a/compat.ypsilon.sls
+++ b/compat.ypsilon.sls
@@ -1,47 +1,47 @@
(library (spon compat)
- (export current-implementation-name
+ (export implementation-name
command
file-copy
make-directory
make-symbolic-link
current-directory
)
(import (rnrs)
(only (core)
current-directory
destructuring-bind
process
process-wait)
(spon config))
- (define (current-implementation-name) "ypsilon")
+ (define (implementation-name) "ypsilon")
(define (command cmd . args)
(destructuring-bind (pid p-stdin p-stdout p-stderr)
(apply process cmd args)
(zero?
(cond ((quiet?)
(process-wait pid #f)) ; nohang = #t
((verbose?)
(let ((p-message (transcoded-port p-stdout (native-transcoder)))
(p-error (transcoded-port p-stderr (native-transcoder))))
(let loop ((status #f))
(when (verbose?)
(let ((message (get-string-all p-message)))
(unless (eof-object? message)
(put-string (current-output-port) message))))
(let ((error (get-string-all p-error)))
(unless (eof-object? error)
(put-string (current-error-port) error)))
(or status (loop (process-wait pid #t)))))))))) ; nohang = #f
(define (file-copy src dst mode)
(command "install" "-m" (number->string mode 8) src dst))
(define (make-directory dir mode)
(command "install" "-m" (number->string mode 8) "-d" dir))
(define (make-symbolic-link target link)
(command "ln" "-sf" target link))
) ;[end]
diff --git a/tools.sls b/tools.sls
index 9bc11cd..a4a0fbb 100644
--- a/tools.sls
+++ b/tools.sls
@@ -1,331 +1,331 @@
(library (spon tools)
(export download verify decompress initialize setup install
system-name verbose? quiet? download-error? download-error-uri
- current-implementation-name command
+ implementation-name command
file-copy make-directory make-symbolic-link
current-directory)
(import (rnrs)
(srfi :39)
(srfi :48)
(spon config)
(spon compat))
(define-condition-type &spon &error
make-spon-error spon-error?)
(define-condition-type &download &spon
make-download-error download-error?
(uri download-error-uri))
(define-record-type (version make-version version?)
(fields
(immutable v1 version-major)
(immutable v2 version-minor)
(immutable v3 version-patch)))
(define-record-type (pkg-stat make-pkg-stat pkg-stat?)
(fields
(immutable status pkg-stat-status)
(immutable version pkg-stat-version)))
(define-record-type (pkg-info make-pkg-info pkg-info?)
(fields
(immutable name pkg-info-name)
(immutable version pkg-info-version)
(immutable depends pkg-info-depends)
(immutable description pkg-info-description)
(mutable status pkg-info-status pkg-info-status-set!)))
(define-syntax do-procs
(syntax-rules ()
((_ (pre cmd ok ng) ...)
(and (begin
(unless (quiet?)
(format #t "----> ~A~%" pre))
(let ((res cmd))
(unless (quiet?)
(if res
(when ok
(format #t "----> ~A~%" ok))
(format #t "----> ERROR: ~A~%" ng)))
res))
...))))
(define (read-package-list)
(define (get-version alis)
(cond ((assq 'version alis)
=> (lambda (xs)
(and (= (length (cdr xs)) 3)
(for-all number? (cdr xs))
(apply make-version (cdr xs)))))
(else #f)))
(let ((ht (make-eq-hashtable)))
(let ((file (format #f "~A/~A" base-path "package-list.sds")))
(when (file-exists? file)
(call-with-input-file file
(lambda (in)
(do ((i (read in) (read in)))
((eof-object? i))
(let ((name (car i))
(version (get-version (cdr i)))
(depends (cond ((assq 'depends (cdr i)) => cdr)
(else #f)))
(description (let ((d (assq 'description (cdr i))))
(and d (apply string-append (cdr d)))))
(status #f))
(hashtable-set! ht name
(make-pkg-info name version depends description status))))))))
(let ((file (format #f "~A/~A" base-path "install.sds")))
(when (file-exists? file)
(call-with-input-file file
(lambda (in)
(do ((i (read in) (read in)))
((eof-object? i))
(let ((name (car i))
(status (and (cadr i) #t))
(version (get-version (cddr i))))
(if (hashtable-contains? ht name)
(let ((p (hashtable-ref ht name)))
(pkg-info-status-set! p
(make-pkg-stat status version))
(hashtable-set! ht name p))
(hashtable-set! ht name
(make-pkg-info name #f #f #f
(make-pkg-stat status version))))))))))
ht))
(define (write-install-status pkg-ht)
(let ((file (format #f "~A/~A" base-path "install.sds")))
(call-with-output-file file
(lambda (out)
(let-values (((ks vs) (hashtable-entries pkg-ht)))
(vector-for-each
(lambda (key val)
(let ((stat (pkg-info-status val)))
(when (pkg-stat? stat)
(write (cons*
key (pkg-stat-status stat)
(if (version? (pkg-stat-version stat))
(list (version->list (pkg-stat-version stat)))
'()))
out)
(newline out))))
ks vs))))))
(define (version<? v1 v2)
(cond ((< (version-major v1) (version-major v2)) #t)
((> (version-major v1) (version-major v2)) #f)
(else
(cond ((< (version-minor v1) (version-minor v2)) #t)
((> (version-minor v1) (version-minor v2)) #f)
(else
(cond ((< (version-patch v1) (version-patch v2)) #t)
(else #f)))))))
(define (version->string version)
(string-append (number->string (version-major version))
"." (number->string (version-minor version))
"." (number->string (version-patch version))))
(define (version->list version)
(list 'version
(version-major version)
(version-minor version)
(version-patch version)))
(define (package->symbol p)
(cond
((symbol? p) p)
((string? p) (string->symbol p))
((pkg-info? p) (pkg-info-name p))
(else #f)))
(define (package->string p)
(cond
((symbol? p) (symbol->string p))
((string? p) p)
((pkg-info? p)
(if (version? (pkg-info-version p))
(string-append (symbol->string (pkg-info-name p))
"-"
(version->string (pkg-info-version p)))
(symbol->string (pkg-info-name p))))
(else #f)))
(define (package-installed? p ht)
(cond
((pkg-info? p)
(let ((stat (pkg-info-status p)))
(if (pkg-stat? stat) (pkg-stat-status stat) stat)))
((symbol? p) (package-installed? (hashtable-ref ht p #f) ht))
((string? p) (package-installed? (string->symbol p) ht))
(else #f)))
(define (cmd-wget uri dir)
(or (apply command
((get-config) "wget")
"-N" "-P" dir uri (if (quiet?) '("-q") '()))
(raise (make-download-error uri))))
(define (cmd-gpg signature file)
(let ((gpg ((get-config) "gpg" #f)))
(or (not gpg)
(apply command
gpg
`(,@(if (quiet?) '("-q") '()) "--verify" signature file)))))
(define (cmd-tar file dir)
(apply command
((get-config) "tar")
"-xzf" file "-C" dir (if (quiet?) '() '("-v"))))
(define (download package)
(let* ((config (get-config))
(download-uri (config "download-uri" download-uri))
(pkg-uri (format "~A/~A.tar.gz" download-uri (package->string package)))
(sig-uri (format "~A.asc" pkg-uri))
(src-path (config "source-path" source-path)))
(do-procs
((format "Downloading package: ~A ..." pkg-uri)
(cmd-wget pkg-uri src-path)
#f
"Failed to download the package")
((format "Downloading signature: ~A ..." sig-uri)
(cmd-wget sig-uri src-path)
#f
"Failed to download the signature"))))
(define (verify package)
(let* ((config (get-config))
(src-path (config "source-path" source-path))
(pkg-file (format "~A/~A.tar.gz" src-path (package->string package)))
(sig-file (format "~A.asc" pkg-file)))
(or (not (config "gpg" #f))
(do-procs
("Veryfying package ..."
(cmd-gpg sig-file pkg-file)
#f
"cannot verify package.")))))
(define (decompress package)
(let* ((config (get-config))
(src-path (config "source-path" source-path))
(pkg-file (format "~A/~A.tar.gz" src-path (package->string package))))
(do-procs
("Decompressing package ..."
(cmd-tar pkg-file src-path)
#f
"error in decompressing package"))))
(define (initialize package mode)
(let* ((config (get-config))
- (impl (current-implementation-name))
+ (impl (implementation-name))
(src-path (config "source-path" source-path))
(pkg-path (format "~A/~A" source-path (package->string package)))
(install.ss (format "~A/install.ss" pkg-path)))
(do-procs
((format "Setup package for ~A ..." (string-upcase system-name))
(parameterize ((current-directory pkg-path))
(command impl install.ss (symbol->string mode)))
#f
(format "error in ~A" install.ss)))))
(define (setup package mode)
(let* ((config (get-config))
- (impl (current-implementation-name))
+ (impl (implementation-name))
(src-path (config "source-path" source-path))
(pkg-path (format "~A/~A" source-path (package->string package)))
(setup.ss (format "~A/setup.ss" pkg-path))
(setup.impl.ss (format "~A/setup.~A.ss" pkg-path impl)))
(do-procs
((format "Setup package to ~A ..." impl)
(parameterize ((current-directory pkg-path))
(command impl
(if (file-exists? setup.impl.ss) setup.impl.ss setup.ss)
(symbol->string mode)))
#f
(format "error in ~A" setup.ss)))))
(define (install package)
(define (install-rec package pkg-ht)
(let ((pi (hashtable-ref pkg-ht (package->symbol package) #f)))
(and (not (package-installed? pi pkg-ht))
(begin
(when (pkg-info? pi)
(let ((depends (pkg-info-depends pi)))
(when depends
(for-each (lambda (dep)
(install-rec dep pkg-ht))
depends))))
(let* ((p (if (pkg-info? pi) pi package))
(package-name (package->string p)))
(let ((r (do-procs
((format "Installing ~A" package-name)
(and (download p)
(verify p)
(decompress p)
(initialize p 'install)
(setup p 'install))
(format "~A is successfully installed.~%" package-name)
(format "~A install failed.~%" package-name)))))
(when r
(if (pkg-info? pi)
(pkg-info-status-set! pi (make-pkg-stat #t (pkg-info-version pi)))
(hashtable-set! pkg-ht
(package->symbol package)
(make-pkg-info package #f #f #f (make-pkg-stat #t #f)))))
r))))))
(let ((pkg-ht (read-package-list)))
(if (package-installed? package pkg-ht)
(begin
(format #t "----> ~A is already installed.~%" (package->string package))
#f)
(let ((r (install-rec package pkg-ht)))
(write-install-status pkg-ht)
r))))
(define (update package)
(define (updatable? pi)
(and (pkg-info? pi)
(let ((stat (pkg-info-status pi)))
(and (pkg-stat? stat)
(version<? (pkg-stat-version stat) (pkg-info-version pi))))))
(define (update-rec package pkg-ht)
(let* ((pi (hashtable-ref pkg-ht (package->symbol package) #f))
(package-name (package->string pi)))
(and (updatable? pi)
(begin
(let ((depends (pkg-info-depends pi)))
(when depends
(for-each (lambda (dep)
(update-rec dep pkg-ht))
depends)))
(let ((r (do-procs
((format "Updating ~A ..." package-name)
(and (download pi)
(verify pi)
(decompress pi)
(initialize pi 'update)
(setup pi 'update))
(format "~A is successfully update.~%" package-name)
(format "~A update failed.~%" package-name)))))
(when r
(if (pkg-info? pi)
(pkg-info-status-set! pi (make-pkg-stat #t (pkg-info-version pi)))
(hashtable-set! pkg-ht
(package->symbol package)
(make-pkg-info package #f #f #f (make-pkg-stat #t #f)))))
r)))))
(let ((pkg-ht (read-package-list)))
(let ((pi (hashtable-ref pkg-ht (package->symbol package) #f)))
(if (updatable? pi)
(let ((r (update-rec package pkg-ht)))
(write-install-status pkg-ht)
r)
(begin
(format #t "----> ~A can't update." (package->string package))
#f)))))
(define (uninstall package)
#f)
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.