Skip to content

Instantly share code, notes, and snippets.

@hidesakai
Created October 19, 2012 04:54
Show Gist options
  • Save hidesakai/3916298 to your computer and use it in GitHub Desktop.
Save hidesakai/3916298 to your computer and use it in GitHub Desktop.
MTのRSS FeedからGoogle Feed API経由でエントリの一覧表示
/*
* このライブラリを呼び出す前に、Google API呼び出しが必要になる
* <script type="text/javascript" src="https://www.google.com/jsapi"></script>
* <script>google.load("feeds", "1");</script>
*
* 実装例:
* $(function(){
* $('rss').feed2node({
* 'uri':'http://***.com/rss.xml',
* 'limit':'5',
* 'parent':'RssNews',
* 'more':'More...',
* 'more_uri':'http://***.com/'
* });
* });
*
* 出力結果:
* <div class="rss">
* <div class="RssNews">
* <dl class="RssNews clearfix">
* <dt>YYYY/MM/DD</dt>
* <dd><a href="http://***.com/***.html">***</a></dd>
* </dl>
* ...
* ...
* </div>
* <p class="RssNews more"><a href="http://***.com/">More...</a></p>
* </div>
*/
(function($){
$.fn.feed2node = function (options){
var target = this;
defaults = {
limit:'',
parent:'',
more:'',
more_uri:'',
feeduri:''
};
var set = $.extend(defaults,options);
var conjuction = '?';
if (getUrlVars(set.uri)) conjuction='&';
set.feeduri = set.uri + conjuction + cacheDate();
readFeeds();
function readFeeds(){
var feed = new google.feeds.Feed(set.feeduri);
feed.setNumEntries(set.limit);
feed.load(function(result){
if (result.error) return false;
var setTarget = $(target).append($('<div></div>').attr({'class':set.parent}));
$.each(result.feed.entries, function(index,elm){
$('div.'+set.parent)
.append($('<dl></dl>').attr({'class':set.parent+' clearfix'})
.append($('<dt></dt>').text(trimDate(this.publishedDate)))
.append($('<dd></dd>').append($('<a></a>').attr({href:this.link}).text(this.title)))
);
});
if (set.more) {
$(target)
.append($('<p></p>').attr({'class':set.parent+' more'})
.append($('<a></a>').attr({href:set.more_uri}).text(set.more))
);
}
});
}
function trimDate(pubDate){
var dt = new Date(pubDate);
return dt.getFullYear() + "/" + addZero(dt.getMonth() + 1) + "/" + addZero(dt.getDate());
}
function addZero(num){
if (num < 10) {
return "0" + num;
} else {
return "" + num;
}
}
function cacheDate(){
var now = new Date();
var minutes = now.getMinutes();
return (now.getMonth() + 1) + '0' + now.getDate() + '0' + now.getHours() + '0' + (minutes - (minutes % 10));
}
function getUrlVars(uri){
if (uri.indexOf('?') == -1) {
return false;
}
var vars = [], hash;
var hashes = uri.slice(uri.indexOf('?') + 1).split('&');
for (var i=0; i < hashes.length; i++) {
hash=hashes[i].split('-');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment